In this post Binding data to DataGridView in C#,
we shall see on how to query data from a SQL Server database and bind the
results to a DataGridView control.
First let us create a new Windows form and add a Button and DataGridView control to the form, the initial form design should be as follows.
First let us create a new Windows form and add a Button and DataGridView control to the form, the initial form design should be as follows.
Once we are done we can navigate to the code view and add the code to get data
from SQL Server and bind the same to the DataGridView.
Since we are going to get the data from SQL Server
database, add a reference to
using System.Data.SqlClient;
Add the following code to the click event of the
Button, to load the DataGridView with data.
private void
btnLoadEmployees_Click(object sender, EventArgs e)
{
// Read the connection string from the app.config file.
string
strConn = ConfigurationSettings.AppSettings["ConnectionString"].ToString();
SqlConnection
objConn = new SqlConnection(strConn);
SqlCommand
objCmd = new SqlCommand("SELECT * FROM EMPLOYEE", objConn);
SqlDataAdapter
objDA = new SqlDataAdapter(objCmd);
DataSet
dsEmployee = new DataSet();
//
objDA.Fill(dsEmployee, "dtEmployee");
//
gvEmployees.DataSource = dsEmployee.Tables["dtEmployee"];
}
Run the application, click on the btnLoadEmployees button,
the DataGridView will
be populated with data from the SQL Server database, the loaded DataGridView
looks
as follows.
That’s it we have populated a DataGridView, with data from a SQL Server database using C# Windows forms.
4 comments:
hi this is really a nice article.
check one link which i found---
http://dotnetpools.com/Article/ArticleDetiail/?articleId=38&title=How%20To%20Bind%20GridView%20In%20Windows%20Application%20Using%20C#
Thank you so much for this!!! Brilliant walk-through, much appreciated :)
Hi, this is very helpful to me..
Bind Data to Custom GridView Control in C# for Windows Forms.
Post a Comment