I have a dataTable bound to a DatagrindView and would like to update a selected column. My DataTable(displayDT) and my datagridview1 have the same layout:
DateTime item1 item2 item3
1/1/2010 100 100 100
1/1/2010 1:00 120 110 90
.
I have 1440 records. I allow the user to update the data by selected column by an amount...so they can select item1 and add an amount to the value in each record. Here is my code I use to run the update:
In my load of the screen:
dataGridView1.DataSource = displayDT;
bindingSourceDG.DataSource = displayDT;
Here is my code that will update the column selected with a Value inputed.
private void btnUpdateColumns_Click(object sender, EventArgs e)
{
try
{
double iValue = double.Parse(txtValue.Text); //user will key in a value that they would like the column to be increased/decreased by
this.Cursor = Cursors.WaitCursor;
//here I am trying to stop the datagridview from syncing up with the datatable after each record changes.
bindingSourceDG.RaiseListChangedEvents = false;
bindingSourceDG.SuspendBinding();
//I created a list of columns the user would like to update by the amount they typed in.
List<int> colIndexList = new List<int>(dataGridView1.Columns.Count);
foreach (DataGridViewColumn col in dataGridView1.SelectedColumns)
colIndexList.Add(col.Index);
// here is my work around to get this process to work faster....with this line of code(the filter) the DataTable will update in a second...without it takes much longer and this is what I do not understand...???? Why does it update so fast with the filter. With the filter applied the 1440 record go down to 24 records. So try a test with and without this line of code.
displayDT.DefaultView.RowFilter = "1 = 1 AND DateTime = '" + iModelStartDate + "'";
//I loop through all the rows in the displayDT and for each column selected I add the value keyed in by the user.
foreach (DataRow dr in displayDT.AsEnumerable())
{
for (int counter = 0; counter < colIndexList.Count; counter++)
{
dr[colIndexList[counter]] = (double)dr[colIndexList[counter]] + iValue;
}
}
// I clear the filter. But you would not need this if running without the "work around"
displayDT.DefaultView.RowFilter = "";
dataGridView1.CurrentCell = null;
bindingSourceDG.RaiseListChangedEvents = true;
bindingSourceDG.ResetBindings(false);
dataGridView1.Refresh();
}
catch
{
MessageBox.Show("Please enter numeric value.", "Enter Numeric");
}
this.Cursor = Cursors.Default;
}