Wednesday, 4 April 2012

Binding DataGridView with data from database

This post will show how to bind Datagridview control in C#.NET, and also how to format columns of datagridview control, eg. hiding some specific columns of the datagridview or setting the width of a particular colums. To bind datagridview following steps should be done:

1. Create a form as shown below



2. Code to bind datagridview

//code for ADD button click
private void btnAdd_Click(object sender, EventArgs e)
{
    try
    {
        //create database connection
        string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        //sql statement to insert information in database
        string sql = "INSERT INTO Person (Name, Age, Email, Phone) VALUES (@Name, @Age, @Email, @Phone)";

        //code to insert into database
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.Parameters.AddWithValue("@Name", txtName.Text);
        cmd.Parameters.AddWithValue("@Age", txtAge.Text);
        cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
        cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
        cmd.CommandType = CommandType.Text;
        int result = cmd.ExecuteNonQuery();

        //check if record has been added to the database
        if (result > 0)
            MessageBox.Show("Record Added!");
        else
            MessageBox.Show("Failed to add!");

        //bind datagridview with data from database
        string query = "SELECT * FROM Person";
        SqlDataAdapter da = new SqlDataAdapter(query, connection);
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
        DataTable dt = new DataTable();
        da.Fill(dt);
        BindingSource bs = new BindingSource();
        bs.DataSource = dt;
        dataGridView1.DataSource = bs;

        //set width of particular datagridview column 
        dataGridView1.Columns[2].Width = 160;

        //hide a particular datagridview column
        dataGridView1.Columns[4].Visible = false;

        connection.close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

2 comments:

  1. An interesting fact about data grid is that A grid supports one or more headers. When a single header is used, the grid has Tree List View control behavior, just like the Microsoft Windows Explorer.

    http://www.dapfor.com/en/net-suite/net-grid/features/headers-and-columns

    ReplyDelete
  2. Data contained in IList, IBindingList or IListSource collections. The grid provides Grid.DataSource property for data binding. Bound collections are convenient for adding and removing data and for complete separation of the data layer from the presentation layer. These collections may also contain objects that implement INotifyPropertyChanged interface. Just like in the unbound mode, the grid subscribes to notifications of these objects and therefore becomes an event-driven grid with automated data sorting, filtering and grouping. more detail visit dapfor. com

    ReplyDelete