Click here to Skip to main content
Licence 
First Posted 26 May 2006
Views 470,676
Bookmarked 52 times

How to populate DataGridView, GridView with SQL statement in C#

By | 26 May 2006 | Article
How to populate DataGridView, GridView with SQL statement in C#
 
Part of The SQL Zone sponsored by
See Also

Introduction

How to populate DataGridView, GridView with SQL statement in C#

 

When we do the development, we always want to make the code simple and error free if possible. In C#, GridView for web based application and DataGridView for windows form based application are different in using and behavior. It looks like Microsoft has two different teams to develop GridView and DataGridView separately.  This is why I wrote this article to share the coding for each control. Here I am using MS Visual Studio 2005.

 

I. Populate GridView control for web based application with SQL statement

 

Let us put GridView1 control on the web form from Toolbox. The coding is straight forward and is like the following:

 

protected void Page_Load(object sender, EventArgs e)

{

 

string strSQLconnection = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";

SqlConnection sqlConnection = new SqlConnection(strSQLconnection);

SqlCommand sqlCommand = new SqlCommand("select * from table1", sqlConnection);

sqlConnection.Open();

 

SqlDataReader reader = sqlCommand.ExecuteReader();

       

GridView1.DataSource = reader;

GridView1.DataBind();

}

 

You run the code and you can see the result. But when you see the data binding for DataGridView in the following section, it is quite different.

 

 

II. Populate DataGridView control with SQL statement for Window form based application

 

When I used the DataGridView control in C# in MS Visual Studio 2005, I found DataGridView control is not friendly to use. Windows form-based DataGridView control is different from web based GridView control. DataGridView doesn’t have DataBind() method.  It took me a few days to figure out.

The logic is like this

  1. Create data set from SQL statement or stored procedure
  2. Create a table to hold this data set
  3. Create a BindingSource and bind this table with this BindingSource
  4. Then bind this BindingSource with GridView control.

 

This looks trivial. But I found it is very efficient and error free.

 

Let us put DataGridView control and BindingSource control on the windows form from Toolbox. Let us name DataGridView control as dbGridView, BindingSource control as dbBindSource. Let us apply the following code:

 

private void Form1_Load(object sender, EventArgs e)

{

string strCon = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";

string strSQL = “select * from table1”;

 

SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);

SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

 

// Populate a new data table and bind it to the BindingSource.

DataTable table = new DataTable();

table.Locale = System.Globalization.CultureInfo.InvariantCulture;

dataAdapter.Fill(table);

dbBindSource.DataSource = table;

 

// Resize the DataGridView columns to fit the newly loaded content.

dbGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

// you can make it grid readonly.

dbGridView.ReadOnly = true; 

// finally bind the data to the grid

dbGridView.DataSource = dbBindSource;

}

 

Now we compile it and run it. You can see the data in the grid.

 

If you have any comments or questions, you can reach me at hong_wei_li@yahoo.com

 

Enjoy C# and happy coding!

- Hongwei Li

 

 

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

hong_wei_li@yahoo.com

Web Developer

United States United States

Member

.Focus on database (SQL Server 2005/2000/7/6.5 and Oracle 10g) development with C#,
 
ASP.NET, ASP, Java, PHP.
.Like to work with MS Server 2005 SSIS and report service
.Like full cycle software design, development and deployment
.Microsoft Certified SQL Server Developer and DBA.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmembercpt_Steel2:09 20 May '12  
QuestionChild list for field " "cannot be created. PinmemberTooze7:45 15 May '12  
GeneralMy vote of 5 Pinmemberhoraceleung5:42 3 May '12  
GeneralMy vote of 4 PinmemberItz.Irshad3:41 28 Dec '11  
GeneralMy vote of 5 Pinmemberkeshavkundal23:02 19 Nov '10  
GeneralMy vote of 4 PinmemberMember 26364401:38 25 Oct '10  
GeneralMy vote of 2 PinmemberKSagar2:04 20 Aug '10  
GeneralMy vote of 1 Pinmemberblackr2d23:05 5 Jul '10  
GeneralMy vote of 1 Pinmemberadolfhardik0:40 11 Jun '10  
Generalmy vote of 2 PinmemberMaximus Byamukama20:56 18 Sep '09  
GeneralMy vote of 1 Pinmemberdemigod23:59 31 May '09  
GeneralRe: My vote of 1 Pinmembersupermankelly2:56 6 Aug '09  
GeneralMy vote of 1 PinmemberUtku KAYA23:20 18 Jan '09  
GeneralMy vote of 2 PinmemberDonsw16:40 26 Nov '08  
GeneralRe: My vote of 2 Pinmembersupermankelly2:54 6 Aug '09  
GeneralRegurgitated Crap Pinmemberpithhelmet4:44 4 Sep '08  
GeneralRe: Regurgitated Crap Pinmembersupermankelly2:53 6 Aug '09  
Generaltry to solve PinmemberNazneen.Insignia20:38 28 Aug '08  
Questionnice copy paste? PinmemberLaoujin22:35 23 Apr '08  
GeneralFilling DataGridView using Stored Procedures PinmemberbuyValu8:34 13 Feb '08  
GeneralRe: Filling DataGridView using Stored Procedures PinmemberGlen Austin12:20 31 Mar '09  
GeneralThanks! Exactly what I was looking for. Pinmembertmpuserz10:16 27 Nov '07  
GeneralQuestion. PinmemberGil.Y14:28 10 Jun '07  
QuestionHow to fill a selected column from a table? Pinmembermwith20:40 31 Dec '06  
AnswerRe: How to fill a selected column from a table? PinmemberBob_Shaw11:12 30 Jan '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 26 May 2006
Article Copyright 2006 by hong_wei_li@yahoo.com
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid