Databinding with DataGridView in ADO.NET

DataGridView is a 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.

DataGrid

Follow the given steps.

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

Property

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

Window

Step 3. Click ComboBox.

ComboBox

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

SourceType

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

DatabaseModel

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

Dataset

Step 7. Click at the New Connection button.

Connection

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

Password

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

Wizard

Step 10. Click the next button.

Button

Step 11. Click on Table to explore all tables of your Database.;

Explore table

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

Explore columns

Step 13. Check the CheckBox to select columns.

Chechbox

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

Details

Run the application.

Output

Output

Now we bind the DataGridView with the 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. The output will be the same as above.

Here are some related resources.


Similar Articles