Reputation: 765
I have a databound
DataGridView
.
To insert a new row I handle DefaultValuesNeeded
.
The new row is displayed with my assigned values. Up to here it works fine.
At this time the row is not yet attached to the underlying DataTable
. That's OK.
The only way to accept the new row is to set any cell in edit mode, change
the value and close the editor.
Now the new row gets added to the DataTable
.
My problem is that I want to add the row with minimal user input.
If the user decides that the values are fine he/she should be able to confirm
without changing some cell values (and setting them back to the original value)
Is there a way to achieve this, e.g. by pressing enter, trap the command and force
the DataGridView
to do the same as if a cell value changed?
I have already tried to change the values in dgv_KeyDown()
without success.
Any suggestions?
private void dgv_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (dgv.CurrentCell != null && dgv.CurrentCell.OwningRow.DataBoundItem == null)
{
//ToDo: Accept the new row
e.Handled = true;
}
}
}
Upvotes: 0
Views: 1268
Reputation: 765
I found the solution.
I have to set the cell state dirty and enter edit mode. Otherwise the internal state will get corrupted when selecting another row
private void dgv_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (dgv.CurrentCell != null && dgv.CurrentCell.OwningRow.DataBoundItem == null)
{
dgv.NotifyCurrentCellDirty(true);
dgv.BeginEdit(true);
e.Handled = true;
}
}
}
Upvotes: 1
Reputation: 7092
My suggestion is, you can using the CellValidating Event and RowValidating Event to achieve this task.
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView1.IsCurrentCellDirty) //or IsCurrentRowDirty
{
if (e.ColumnIndex == 1)
{
if (MessageBox.Show("You're about to change the value. Do you want to continue?\n\nPress ESC to cancel change.",
"Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information) != System.Windows.Forms.DialogResult.OK)
{
e.Cancel = true;
}
}
}
}
Upvotes: 0