Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

C# - Using Statement Example | Uses of Using Statement in C#

Aug 29, 2013
Introduction:

In this article I will explain uses of using statement in c# and how to declare and use using statement in c#, vb.net,
Asp.net.

Description:

In Previous posts I explained lot of articles regarding
Asp.net, Gridview, SQL Server, Ajax, JavaScript etc. Now I will explain about using statement in c#.

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 = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand (commandString, con);
cmd.ExecuteNonQuery();
con.Close();
It’s very easy way to write above code but problem is SqlConnection and 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 = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand (commandString, con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}
VB.NET Code

Using con As New SqlConnection(connectionString)
Using cmd As New SqlCommand(commandString, con)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
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 using statement code will equal to below code


SqlConnection con = null;
SqlCommand cmd = null;
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand(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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
After that open code behind page and add the following namespace references

using System;
using System.Configuration;
using System.Web.Configuration;
After add namespaces write the following code in code behind

C# code

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
//Bind Data to Repeater Control
protected void BindGridviewData()
{
string connectionString = "Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true";

using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd=new SqlCommand("select * from Repeater_Table Order By PostedDate desc",con))
{
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
}
}
VB.NET Code

Imports System.Data
Imports System.Data.SqlClient

Partial Class Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridviewData()
End If
End Sub
'Bind Data to Repeater Control
Protected Sub BindGridviewData()
Dim connectionString As String = "Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true"
Using con As New SqlConnection(connectionString)
Using cmd As New SqlCommand("select * from Repeater_Table Order By PostedDate desc", con)
con.Open()
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
gvDetails.DataSource = dt
gvDetails.DataBind()
End Using
End Using
End Sub
End Class


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

9 comments :

Maulin said...
This comment has been removed by the author.
Maulin said...

What if we define this objects in Constructor and then use them in the method


Is this a better approach ?

for example;

public class PreScreen
{
public int AdvertId { get; set; }
public int QueId { get; set; }
public string QueType { get; set; }
public string Question { get; set; }

SqlConnection ConSqlClust, ConKimchi;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da;
string query;
DataSet ds;

public PreScreen()
{
ConSqlClust = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlClustConnectionString"].ConnectionString);
ConKimchi = new SqlConnection(ConfigurationManager.ConnectionStrings["KimchiConnectionString"].ConnectionString);
ds - new DataSet();
dr = new SqlDataReader
}

public DataSet GetPreScreen(int AdId, string Scope)
{
cmd = new SqlCommand("SP_Advert_GetPreScreenQuestions", ConKimchi);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Scope", Scope);
cmd.Parameters.AddWithValue("@AdvertId", AdId);
da = new SqlDataAdapter(cmd);

try
{
ConKimchi.Open();
da.Fill(ds);
}
catch (Exception ex)
{
Email.SendErrorMessage(ex);
}
finally
{
ConKimchi.Close();
}

if (ds.Tables[0].Rows.Count == 0)
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
}
return ds;
}
}

karthik said...

USING statement creates try/finally blocks automatically .can you please tell how to handle errors with USING statement in c# how it handles exceptions .

Anonymous said...

Hi suresh,
thanks for article but am getting an error in user code
invalid object name

Anonymous said...

how to show data in data gridview from database in c#.

Unknown said...

Hi Suresh,

Great Article .... Keep rocking....

Please also explain about dictionary object to read plus write in Excel sheet .....

Regards,


Diwan Bisht said...

Please also explain about dictionary object to read plus write in Excel sheet .....

Regards,

Unknown said...

Your explanation is excellent.

Unknown said...

Your explanation is excellent.

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.