C# Commit changes in DataGridView to DataTable

cdatagridviewdatatable

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!

Best Answer

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.