C# – How to Update data in DataGrid

ccompact-frameworkwindows-mobile

I am trying to update my DataGrid but unfortunately not able to! My application have a DataGrid to which data is loaded from a CSV file. Some of the data needs to get updated. But I am not able to find the right way to reflect the updates on the grid.

Here is what I have so far:

// Creation of my DataGrid
this.dataSource = new DataSet();
DataTable data = new DataTable("Products");    


data.Columns.Add("Note", System.Type.GetType("System.String"));
data.Columns.Add("Details", System.Type.GetType("System.String"));
data.Columns.Add("Net", System.Type.GetType("System.String"));
data.Columns.Add("Empty Weight", System.Type.GetType("System.String"));
data.Columns.Add("Full Weight", System.Type.GetType("System.String"));
data.Columns.Add("Description", System.Type.GetType("System.String"));
data.Columns.Add("UOM", System.Type.GetType("System.String"));
data.Columns.Add("Item", System.Type.GetType("System.String"));

dataSource.Tables.Add(data);
dataGrid1.DataSource = data;

When User press a "Load" button, I load the data to my grid:

DataTable vehicle = dataSource.Tables[0];
.
. // data is read from CSV
.
vehicle.Rows.Add("A sample note", "...", full - empty, empty, full, "Test description", "Gr", i); // an example

Here is how I tried to update the data on the grid:

DataTable vehicle = dataSource.Tables[0];
vehicle.Rows[0].BeginEdit();
vehicle.Rows[0].ItemArray[0] = "TEST COMPLETE";            
vehicle.Rows[0].EndEdit();
vehicle.AcceptChanges();
dataGrid1.Update();

But there is no update to the grid.. What am I missing?

Best Answer

I've never gotten tools like Update or AcceptChanges to work the way I want them to. I suspect they do something different than what seems obvious to me.

Also, I have no knowledge if a separate DataTable is linked (i.e. via an underlying pointer). Making a change to the DataTable may or may not translate to changing the data stored in the DataGridView.

For me, I reassign it.

private void UpdateTheDataGrid() {
  DataTable vehicle = (DataTable)dataGrid1.DataSource;
  // vehicle.Rows[0].BeginEdit(); <- Unsure if this is even needed
  vehicle.Rows[0].ItemArray[0] = "TEST COMPLETE";            
  // vehicle.Rows[0].EndEdit();
  vehicle.AcceptChanges();
  dataGrid1.DataSource = vehicle;
}

Another technique would be to work directly with the DataGridView control itself:

private void UpdateTheDataGrid() {
  dataGrid1.Rows[0].Cells[0].Value = "TEST COMPLETE";
}

NOTE to Above: I do not have VS running, so I'm not sure if that code is 100% accurate, but it should give you the idea.

As a comment, I am interested to know if there is any difference between your version of adding a column and the version I use:

// Yours
data.Columns.Add("Note", System.Type.GetType("System.String"));

// Mine
data.Columns.Add("Note", typeof(string));