Please explain me what is happening. I have created a WinForms .NET application which has DataGridView on a form and should update database when DataGridView inline editing is used.
Form has SqlDataAdapter _da with four SqlCommands bound to it. DataGridView is bound directly to DataTable _names.
Such a CellValueChanged handler:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
_da.Update(_names);
}
does not update database state although _names DataTable is updated. All the rows of _names have RowState == DataRowState.Unchanged
Ok, I modified the handler:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataRow row = _names.Rows[e.RowIndex];
row.BeginEdit();
row.EndEdit();
_da.Update(_names);
}
this variant really writes modified cell to database, but when I attempt to insert new row into grid, I get an error about an absence of row with index e.RowIndex
So, I decided to improve the handler further:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (_names.Rows.Count<e.RowIndex)
{
DataRow row = _names.Rows[e.RowIndex];
row.BeginEdit();
row.EndEdit();
}
else
{
DataRow row = _names.NewRow();
row["NameText"] = dataGridView1["NameText", e.RowIndex].Value;
_names.Rows.Add(row);
}
_da.Update(_names);
}
Now the really strange things happen when I insert new row to grid: the grid remains what it was until _names.Rows.Add(row); After this line THREE rows are inserted into table - two rows with the same value and one with Null value.
The slightly modified code:
DataRow row = _names.NewRow();
row["NameText"] = "--------------"
_names.Rows.Add(row);
inserts three rows with three different values: one as entered into the grid, the second with "--------------" value and third - with Null value.
I really got stuck in guessing what is happening.