Build a DataTable and bind it to a DataGridView in C#

Build a DataTable and bind it to a DataGridView

This example shows how you can build a DataTable and bind it to a DataGridView control. A DataTable is an in-memory representation of a relational database table. It can define columns of particular data types and even enforce uniqueness and foreign key constraints. This example shows how to build a DataTable in code that uses specific data types for its columns and that has a two-column uniqueness constraint.

When the program starts, the following code creates and displays the DataTable.

private void Form1_Load(object sender, EventArgs e)
{
    // Make the DataTable object.
    DataTable dt = new DataTable("People");

    // Add columns to the DataTable.
    dt.Columns.Add("First Name",
        System.Type.GetType("System.String"));
    dt.Columns.Add("Last Name",
        System.Type.GetType("System.String"));
    dt.Columns.Add("Occupation",
        System.Type.GetType("System.String"));
    dt.Columns.Add("Salary",
        System.Type.GetType("System.Int32"));

    // Make all columns required.
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        dt.Columns[i].AllowDBNull = false;
    }

    // Make First Name + Last Name require uniqueness.
    DataColumn[] unique_cols = 
    {
        dt.Columns["First Name"],
        dt.Columns["Last Name"]
    };
    dt.Constraints.Add(new UniqueConstraint(unique_cols));

    // Add items to the table.
    dt.Rows.Add(new object[]
        {"Rod", "Stephens", "Nerd", 10000});
    dt.Rows.Add(new object[]
        {"Sergio", "Aragones", "Cartoonist", 20000});
    dt.Rows.Add(new object[]
        {"Eoin", "Colfer", "Author", 30000});
    dt.Rows.Add(new object[]
        {"Terry", "Pratchett", "Author", 40000});

    // Make the DataGridView use the DataTable as its data source.
    dgvPeople.DataSource = dt;
}

This code makes a DataTable object and adds columns to it, specifying their data types. It then loops through all of the columns setting their AllowDBNull properties to false so each column is required.

Next the program makes an array containing the First Name and Last Name columns. It uses that array to make a UniqueConstraint object and adds it to the DataTable object’s Constraints collection.

Finally the program uses the DataTable‘s Rows.Add method to add arrays of objects to the DataTable. It finishes by setting the DataGridView control’s DataSource property to the DataTable. The DataGridView and DataTable display the data automatically.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, database and tagged , , , , , , , , , , , . Bookmark the permalink.

9 Responses to Build a DataTable and bind it to a DataGridView in C#

  1. Pingback: Handle DataGridView errors in C# - C# HelperC# Helper

  2. Alex says:

    Can you please help me with a very similar situation?

    • RodStephens says:

      If you post questions here, I’ll try to answer.

      • Pechi says:

        Hi, I am trying to display the selected row from data table to datagridview, I created the datagrid grd.

        
        private void btnView_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), 
                new DataColumn("Name", typeof(string)), 
                new DataColumn("Country",typeof(string)) });
            dt.Rows.Add(1, "John Hammond", "United States");
            dt.Rows.Add(2, "Mudassar Khan", "India");
            dt.Rows.Add(3, "Suzanne Mathews", "France");
            dt.Rows.Add(4, "Robert Schidner", "Russia");
            DataRow[] rows = dt.Select("Id = 2"); 
            //var dr = dt.Select("Id = 2");
            //grd.DataSource = DataRow[rows];
            //grd.FirstDisplayedScrollingRowIndex = grd.SelectedRows[0].Index;

        I want to display only the 2nd row in my datagridview.

        Thanks in advance!

        • RodStephens says:

          You could create a second DataTable and put the selected row in it. Then bind the DataGridView to that DataTable.

          If bind the whole DataTable to the grid and then select the row in the DataTable, I think the DataGridView should scroll to highlight the selected row.

  3. Roberto C. says:

    Emm what if you want to add rows manually ? It gives an error

    • RodStephens says:

      That’s not really what this example is about, but you can add rows to the table and the DataGridView will display them. Or you can add them interactively in the DataGridView.

  4. zultum says:

    thanks for the awesome example…how about an example of binding data (rows) to a DATGRIDVIEW already designed in c# form?

    • RodStephens says:

      I don’t understand what you want. If you mean adding new rows, then you can add them to the DataTable and the DataGridView will display them. If you mean you have already added rows to the control and now want to bind new ones, I don’t think you can do that. I would move the existing rows into a DataTable, bind that, and go from there.

Leave a Reply

Your email address will not be published. Required fields are marked *