Geeks With Blogs

News

Microsoft MVP


Moderator at CodeASP.NET


Quiz Master




free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

This example demonstrates how to populate GridView with data from the database using the ADO.NET way.
Before you proceed reading this example be sure that you know the basics of ADO.NET manipulation. If you are not familiar with ADO.NET then I would suggest you to refer at the following link below:

ADO.NET Tutorial


STEP 1: Setting up the Connection String

- Open your Web.config file and set up your connection string like below:

<connectionStrings>
    <add name="MyDBConnection" connectionString="Data Source=WPHVD185022-9O0;
                               Initial Catalog=Northwind;
                               Integrated Security=SSPI;"
                               providerName="System.Data.SqlClient"/>
</connectionStrings>



STEP 2: Create the GetConnectionString() method

- Create a method for accessing your connection string that was set up at the Web.config file

private string GetConnectionString(){
 return ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
}

Note: MyDBConnection is the name of the connectionstring that was set up in the webconfig.

STEP 3: Setting up the GridView in the mark up (ASPX)

- Grab a GridView from the Visual Studio ToolBox and then Set AutoGenerateColumns to False.
- Add BoundField Columns in GridView and set the DataField and the HeaderText accordingly. See below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
             "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Populating GrindView Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="CompanyName"  HeaderText="Company"/>
            <asp:BoundField DataField="ContactName" HeaderText="Name"/>
            <asp:BoundField DataField="ContactTitle" HeaderText="Title"/>
            <asp:BoundField DataField="Address" HeaderText="Address"/>
        </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>


STEP 4: Create the BindGridView() method

- After setting up your GridView in the mark up then switch back to Code behind
- Declare the following NameSpace below so that we can use the SqlClient built-in libraries

using System.Data.SqlClient;


-Create the method for Binding the GridView

private void BindGridView()
{ 

        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection(GetConnectionString()); 

        try
        {
          connection.Open();
          string sqlStatement = "SELECT * FROM Customers";
          SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
          SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
          sqlDa.Fill(dt);

              if (dt.Rows.Count > 0)
              {
                GridView1.DataSource = dt;
                GridView1.DataBind();
              }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
                string msg = "Fetch Error:";
                msg += ex.Message;
                throw new Exception(msg);
        }
        finally
        {
            connection.Close();
        }
}


STEP 5: Calling the BindGridView() method on initial load of the page.

protected void Page_Load(object sender, EventArgs e){
        if (!Page.IsPostBack){
            BindGridView();
        }
}


STEP 6: Displaying the Output in the page


- Compile and run your page to see the output.. see below




That simple!

Technorati Tags: ,,,
Posted on Thursday, February 19, 2009 9:35 PM ADO.NET , ASP.NET , C# , GridView | Back to top


Comments on this post: Binding GridView with Data - The ADO.NET way

# Binding GridView with Data
Requesting Gravatar...
this explanation was really great.
beaing a freasher i really enjoyed reading this
Left by Syed Nadeem on May 27, 2009 1:12 AM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
its an awesome tutorial for beginners.
Thanks a lot
Left by hrishikesh on Jun 02, 2009 8:36 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
Thanks buddy!
Good one!!
Left by neeraj on Jan 28, 2010 2:19 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
Where do we write the code for Step 2 in the application?
Left by BhanuChandra on Jul 14, 2010 5:20 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
Really Great Artical
Very Helpful
:-)
Left by Kartik Tankaria on Dec 21, 2010 6:19 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
It's best one.But also i have a suggestion.In the second step where will we write the coding in our application.plz reply soon.
Left by sridharan on Jan 21, 2011 4:20 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
@sridharan,

You can put in your code behind page. Or you can create a separate class for your connection string and reference that method from there.
Left by Vinz on Jan 21, 2011 4:30 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
NICE THANKS
Left by rubia on Jul 04, 2011 10:48 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
Binding GridView with Data - The ADO.NET way
this is very very nice code and easily learn away
Left by jagadishwar on Nov 05, 2011 6:01 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
Really Good ......... as a fresher i can understand easily
Left by Ramasamy on Nov 30, 2011 6:17 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
Really its too good for me nd those who r fresher.............
thanks
Left by Amit anand on Jan 25, 2012 5:42 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
Your article are really awesome Actually I was in search for some good articles on DataView in ADO.Net and finally I got one.
The most important thing of this article is the simplicity which makes it very helpful for the beginners. Check this links..
http://mindstick.com/Blog/151/Dataview%20in%20ADO%20Net

http://www.vbdotnetheaven.com/uploadfile/dbeniwal321/dataview-in-ado-net/

It also having nice post on DataView in ADO.Net with wonderful explanation.
Left by Somesh Batra on Mar 23, 2012 5:55 PM

# re: Binding GridView with Data - The ADO.NET way
Requesting Gravatar...
Thank you... Very helpful!!!
Left by Bill New on May 08, 2012 5:19 AM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net | Join free