Thursday, 21 October 2010

C# .net Insert a Column into DataTable Source and Refresh DataGridView

Inserting rows at a particular point in a DataTable is easy, inserting columns was a bit trickier as the DataGridView didn't update or refresh its view of the DataSource;

if (dataGridView.SelectedCells.Count > 0)
{
  int selectedCellCol = dataGridView.SelectedCells[0].ColumnIndex;
  DataColumn newColumn = new DataColumn();
 
  // Set properties of the new column
  workingDataSet.Tables[0].Columns.Add(newColumn);
  newColumn.SetOrdinal(selectedCellCol);
  this.dataGridView.DataSource = null;
  this.dataGridView.DataSource = workingDataSet.Tables[0];
               
  this.dataGridView.Refresh();
 }

It seems setting the DataSource to null, followed by pointing it back at the DataTable source forced the data in the DataGridView to refresh.

No comments:

Post a Comment

Thanks for the feedback!