Generally in our applications we will
write code like create connection object to handle connectionstring after that
open a connection and create command object etc. to interact with database to
get data that would be like this

SqlConnection con = newSqlConnection(connectionString);

con.Open();

SqlCommand cmd = newSqlCommand (commandString, con);

cmd.ExecuteNonQuery();

con.Close();

It’s very easy way to write above code
but problem is SqlConnectionand SqlCommand objects will create IDISPOSABLE interface that means it could create
unmanaged resources in our application to cleanup those objects we need to call
Dispose() method at the end of our process otherwise those objects will remain
in our application.

Suppose we use using statement in our applications it will automatically create
try / finally blocks for the objects and automatically runs Dispose() method for us no need to
create any try/finally block and no
need to run any Dispose() method.

If we use using statement we need to
write code will be like this

C#
Code

using (SqlConnection
con = newSqlConnection(connectionString))

{

using (SqlCommand
cmd = newSqlCommand
(commandString, con))

{

con.Open();

cmd.ExecuteNonQuery();

}

}

VB.NET
Code

Using con AsNew SqlConnection(connectionString)

Using cmd AsNew SqlCommand(commandString, con)

con.Open()

cmd.ExecuteNonQuery()

EndUsing

EndUsing

In above code using statement no need to worry about close connection because using statement automatically close the connection once process
is complete and automatically it will run Dispose()
method to dispose objects.

The above usingstatement code will equal to below code

SqlConnection con = null;

SqlCommand cmd = null;

try

{

con = newSqlConnection(connectionString);

cmd = newSqlCommand(commandString, con);

con.Open();

cmd.EndExecuteNonQuery();

}

finally

{

if (con != null)

con.Dispose();

if (cmd != null)

cmd.Dispose();

}

Sample
Code to display data in gridview by using statement

First
open Default.aspx page and write the
following code

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<asp:GridViewID="gvDetails"runat="server">

</asp:GridView>

</div>

</form>

</body>

</html>

After
that open code behind page and add the following namespace references