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",
    dt.Columns.Add("Last Name",

    // 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.

20 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.

  5. UnniMeena says:

    This was excellent. But how to add to dataGridView from a data table each time new data when I click on a button.

    • UnniMeena says:

      I understand my question is not correct or unclear. I think based on the questions already above, the purpose of the data table is to add whatever in there in the data table to datagrid view in one go. If subsequent additions to be made to the data table, I should add it data datable and later refresh the datagrid view with the new data source ie. the data table. Or I should programmatically add the new data to data grid view. Am I right?

  6. Pingback: Update a DataTable that is bound to a DataGridView in C# - C# HelperC# Helper

  7. Sinan says:

    May be it is a wrong point to mention that how about to delete a row from dt and removeAt DataGridView also too

    • RodStephens says:

      The user can highlight a row and press Delete to remove that row. That also removes if from the underlying DataTable.

      Similarly, you can remove it from the DataTable in code (as in dt.Rows.RemoveAt(1);) and the DataGridView updates.

  8. Pingback: Change a DataGridView entry when the user double-clicks a cell in C# - C# HelperC# Helper

  9. Lakshman says:

    I want to Build a DataTable and bind it to a DataGridView in C#
    and the data inserted in datatable coming from textboxes at run time,so I want to insert more numbers of rows in datatable
    please help me

  10. Manuele says:

    This doesn’t work for me

    I mean dataTable is populated but datagridview doesn’t display anything


    • RodStephens says:

      It works for me. Be sure the DataTable is declared at the class level so the code that modifies it can see the same DataTable that you attached to the DataGridView.

      If you can’t figure it out, zip up the project and email it to me and I’ll take a look.

Comments are closed.