Databinding with DataGridView in ADO.NET


DataGridView is very powerful and flexible control for displaying records in a tabular (row-column) form. Here I am describing a different way of databinding with a DataGridView control.

Take a windows Form Application -> take a DataGridView control.

 

Follow the given steps.

Step 1 :
Select DataGridView control and click at smart property. Look at the following figure.



Step 2 : After clicking, a pop-up window will be open.



Step 3 : Click ComboBox.



Step 4 : Click at Add Project Data Source (Look at above figure). A new window will be opened to choose Data Source Type.



Step 5 : Choose Database (By default it is selected) and click the next button. A new window will be open to Database Model.



Step 6 : Select DataSet (By default it is selected) and click the next button. A new window will be open.



Step 7 : Click at New Connection button.



Step 8 : Write Server name, User name and Password of your SQL server and select Database name. Look at the following figure.

Step 9 : Click "ok" button. After clicking ok button, you will reach the Data Source Configuration Wizard.

Step 10 : Click the next button.

Step 12 : Click on Table to explore all tables of your Database. 



Step 13 : Click on the selected Database table to explore all columns.



Step 14 : Check the CheckBox to select columns.



Step 15 : Click the Finish button. You will note that the DataGridView will show all columns of the table (Here, "Student_detail").



Run the application.

Output

Now we bind the DataGridView with database by code. Take another DataGridView control and write the following code on the form load event.

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
DatabindingWithdataGridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SqlDataAdapter dadapter;
        DataSet dset;
        string connstring = "server=.;database=student;user=sa;password=wintellect";
        private void Form1_Load(object sender, EventArgs e)
        {
            dadapter = new SqlDataAdapter("select * from student_detail", connstring);
            dset = new System.Data.DataSet();
            dadapter.Fill(dset);
            dataGridView1.DataSource = dset.Tables[0].DefaultView;
        }
    }
}
 
Run the application. Output will be same as above.

Here are some related resources

DataBinding with DataGridView in FSharp

Database Updates From DatagridView

Searching Record in DataGridView in ADO.NET

Up Next
    Ebook Download
    View all
    Learn
    View all