Click here to Skip to main content
15,890,043 members
Articles / Web Development / ASP.NET
Article

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

Rate me:
Please Sign up or sign in to vote.
2.97/5 (43 votes)
26 May 20062 min read 791.6K   55   41
How to populate DataGridView, GridView with SQL statement in C#

Introduction

<o:p>

How to populate DataGridView, GridView with SQL statement in C#<o:p>

<o:p> 

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.<o:p>

<o:p> 

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

<o:p> 

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

<o:p> 

protected void Page_Load(object sender, EventArgs e)<o:p>

{<o:p>

<o:p> 

string strSQLconnection = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";<o:p>

SqlConnection sqlConnection = new SqlConnection(strSQLconnection);<o:p>

SqlCommand sqlCommand = new SqlCommand("select * from table1", sqlConnection);<o:p>

sqlConnection.Open();<o:p>

<o:p> 

SqlDataReader reader = sqlCommand.ExecuteReader();<o:p>

        <o:p>

GridView1.DataSource = reader;<o:p>

GridView1.DataBind();

}

<o:p> 

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.

<o:p> 

<o:p> 

II. Populate DataGridView control with SQL statement for Window form based application<o:p>

<o:p> 

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.

<o:p> 

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

<o:p> 

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:

<o:p> 

private void Form1_Load(object sender, EventArgs e)

{

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

string strSQL = “select * from table1”;

<o:p> 

SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);

SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

<o:p> 

// 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;

<o:p> 

// 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;

}

<o:p> 

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

<o:p> 

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

<o:p> 

Enjoy C# and happy coding!

- Hongwei Li

<o:p> 

 

 

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


Written By
Software Developer (Senior)
United States United States
C# and .NET Core
Typescript, node.js, jQuery, jQuery Mobile
Web Api and MVC
Angular and AngularJS
Azure
Databases (SQL Server and Oracle) and No-SQL Databases
Agile and Waterfall

Comments and Discussions

 
GeneralQuestion. Pin
Gil.Y10-Jun-07 14:28
Gil.Y10-Jun-07 14:28 
QuestionHow to fill a selected column from a table? Pin
mwith31-Dec-06 20:40
mwith31-Dec-06 20:40 
AnswerRe: How to fill a selected column from a table? Pin
Bob_Shaw30-Jan-07 11:12
Bob_Shaw30-Jan-07 11:12 
GeneralSave DataGridView Changes to Database Pin
freshonlineMax23-Nov-06 20:37
freshonlineMax23-Nov-06 20:37 
AnswerRe: Save DataGridView Changes to Database [modified] Pin
MBrooker30-Nov-06 10:43
MBrooker30-Nov-06 10:43 
GeneralOledb Pin
UltraWhack8-Nov-06 4:14
UltraWhack8-Nov-06 4:14 
GeneralRe: Oledb Pin
hong_wei_li@yahoo.com14-Nov-06 10:00
hong_wei_li@yahoo.com14-Nov-06 10:00 
GeneralFill takes too long for 1000s of records Pin
UltraWhack23-Oct-06 11:28
UltraWhack23-Oct-06 11:28 
GeneralRe: Fill takes too long for 1000s of records Pin
Rob Graham23-Oct-06 12:07
Rob Graham23-Oct-06 12:07 
GeneralRe: Fill takes too long for 1000s of records Pin
UltraWhack23-Oct-06 16:14
UltraWhack23-Oct-06 16:14 
GeneralRe: Fill takes too long for 1000s of records Pin
supermankelly6-Aug-09 3:02
supermankelly6-Aug-09 3:02 
GeneralJust few lines of code to populate a DataGridView Pin
Rosario1008-Sep-06 0:08
Rosario1008-Sep-06 0:08 
GeneralFill with large table Pin
Wouter Van Ranst13-Jul-06 7:23
Wouter Van Ranst13-Jul-06 7:23 
GeneralRe: Fill with large table Pin
hong_wei_li@yahoo.com17-Jul-06 8:41
hong_wei_li@yahoo.com17-Jul-06 8:41 
NewsWhy is 5000 rows a problem Pin
mwortman11-Jan-07 8:59
mwortman11-Jan-07 8:59 

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

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