Update a DataTable that is bound to a DataGridView in C#


The example Build a DataTable and bind it to a DataGridView in C# shows how you can bind a DataTable to a DataGridView to display data. This example shows how you can add new data to the display.

When the user clicks the Add button, the example program executes the following code.

private void btnAdd_Click(object sender, EventArgs e)
    NewItemDialog dlg = new NewItemDialog();
    if (dlg.ShowDialog() == DialogResult.OK)
        // Make the DataTable object.
        DataTable dt = (DataTable)dgvPeople.DataSource;

This code displays a dialog where you can enter a new name, occupation, and salary. If you click Ok, the program gets the DatagridView control’s DataSource. The form’s Load event handler set that object equal to a DataTable. (See the previous example for details.)

The program converts the DataSource into a DataTable. It then adds the data that you entered on the dialog as a new row in the DataTable. The DataGridView automatically updates its display to show the new data.

This example shows how you can add a row to the DataTable, but you should be able to manipulate it in other ways, too. For example, you should be able to remove rows from the DataTable and the DataGridView should show the result.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in controls, database and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Update a DataTable that is bound to a DataGridView in C#

  1. Manoj Madushantha says:

    What about removing row or change order by clicking column header.

Comments are closed.