C# Commit changes in DataGridView to DataTable

19,309

Solution 1

There's no way to create a table automatically from the DataGridView columns (EDIT To refine this: There are ways to automatically create database structures - ORM would be a good keyword here - but I guess that's not what you need). The other way round works well: Create the table and assign it to the DataGridView as its data source. Then the grid should show the respective columns.

"Storing" the values in the data table works only if you have "told" the columns, which field of the underlying table they relate to. That is: You need to create the table columns (it has a name), and when you create the DataGridView column, you need to assign the column name to the DataPropertyName property of the column.

Easiest way for you: Create a typed dataset (use the "Add to project" dialog to add a new "DataSet"), manually create a table in the dataset's designer, drag an instance of your dataset to the form and assign this as the data source to your DataGridView. Everything else should appear automatically.

Solution 2

I hope you this links from codeproject might help:

http://www.codeproject.com/Questions/80935/save-datagrid-data-to-database

http://www.codeproject.com/Articles/12846/Auto-Saving-DataGridView-Rows-to-a-SQL-Server-Data

Solution 3

If your DataTable is set as the DataSource for the dataGridView, the contents in the dataGridView will reflect the data in the DataTable and vice versa. Therefore, if you make changes to the dataGridView, those changes are already in the DataTable.

Share:
19,309
Zura
Author by

Zura

Updated on June 04, 2022

Comments

  • Zura
    Zura almost 2 years

    I need an example of code or project with one DataGridView Form and one DataTable so I can edit DataGridView cells and then all the changes are automatically commited into the DataTable. Also how can I create DataTable with the same columns with DataGridView other way that manually?

    I tried to create DataGridView and DataTable with the same columns manually and then set the DataGridView.DataSource = DataTable, but data saved into the table are null (anyway number of new rows is correct, but values are invalid).

    Tried to google it - all the samples and questions are about savind into DataBase, but I don't need a DB, I just need a simple DataTable and DataGridView binding.

    Thanks!

  • technonaut
    technonaut over 3 years
    This generated a Unable to cast object of type 'System.Data.DataTable' to type 'System.Data.DataView'. exception. It is an interesting idea though, so I changed it to Dim dt As DataTable = CType(Me.DataGridView1.DataSource, DataTable) to see what happens. It actually did a conversion (sort of) without error, but there were no rows in the table - the resulting table didn't actually contain the data from the datagridview.