Bind DataGridView in Window Forms Using C#

We use one GridView and a database. We enter some data into the database and then bind that data to a GridView.

Step 1

Open your Visual Studio 2010 then go to File -> New -> Project then under Visual C# select the Windows node.
new project
You can change the name of the project and you can browse to create your project in a different location too. And then press OK.

Step 2

In Solution Explorer you get your project, then add a Service-Based database by going to your project then right-click and Add New Item then select Service Based database.
Identity Specification

Step 3

Get to your database (Database.mdf). We will create a table (tbl_Data). Go to the database.mdf then select Table then select Add New table. Design your table like this:
Table -> tbl_data (Don't forget to set ID -> Identity Specification -> Yes).

Step 4

Now open your Form1.cs file where we created our design for GridView binding.
We will drag a DataGridView from the toolbox to Form1.cs. You will see your form look like the following.
add field
You will see your GridView is empty when you dragged it to the form, we must add these headers for ID, Name and City By Going like this.
Right-click on the small arrow on the GridView then select Edit Column. The Edit Column window will open, on the bottom-left there is an “ADD” button, click on that. You will see an Add Colum window will open like this. 
There you must add a field as we do for a bound field in ASP.NET. Here I had done it for Id. You must only do the same for name and city.
add column
After adding all that you will see something like these images.


Here in the Bound Column Property there is a field, Data Property Name. It is the same as a Data Field in ASP.Net, so you must do something with Data Property Name, like for Id I had Included Id in my database, then for Name, name; for City, city. So fill that out and press OK.

using System;  

using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Windows.Forms;  
using System.Data.SqlClient;  
namespace WindowsFormsApplication3  
    public partial class Form1 : Form  
        public Form1()  
            private void refreshdata()  
                SqlConnection con = new SqlConnection(" Data Source=W3asp;Initial Catalog=W3asp;Integrated Security=True;User Instance=True");  
                SqlCommand cmd = new SqlCommand("select * from tbl_data",con);  
                SqlDataAdapter sda = new SqlDataAdapter(cmd);             
                DataTable dt = new DataTable();  

Need Help? Contact Us.

Log in


Forgot password?


New User