How to Bind DataGridView with DataSet in Windows Forms: ADO.NET

In our previous post, I have described about the ways to bind datagridview in windows forms. The first way is to bind the datagridview with dataset and show the data of a table in the gridview. Here is the syntax of binding in c#:
dataGridView.DataSource= ”DataSet Name”;
dataGridView.DataMember=”Table Name”;

Now the time is to perform this code with our existing dataset and table. Drag-n-drop a datagridview on the window and write the following c# code in our form’s constructor:
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source=(LocalDb)\\v11.0; Initial Catalog=StockDb; Integrated Security=True";

SqlCommand command = new SqlCommand("select * from Groups", connection);

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(command);

dataGridView1.DataSource = ds;
dataGridView1.DataMember = ds.Tables[0].ToString();

In the above code, first four lines are same as written in executing sql statements. Fifth line will create a new object of DataSet. Six line will create an object of SqlDataAdapter class which will create an adapter with specified command object.

Next line tell us to fill the dataset with the adapter, which contains all the rows returning by the command object.

Now the last two lines are used to specify the data source of datagridview and the table which will be bind to. When we run the code a window will show with a datagridview containing all the returning rows as shown in following image:

How to bind DataGridView with dataset in Windows Forms ADO.NET

Subhash Sharma

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google

1 comment: