請教:如何取消DataGridView的修改?
我在DataGridView中某cell值修改後,一段程式做資料檢查,如發現有不合理的將取消修改,變更至修改前的值,請教如何做?
祝豬年發達!
------解决方案--------------------在数据库放个预修改字段?
------解决方案--------------------MARK
------解决方案--------------------将datagridview的CauseValidation属性设置为True,然后你可以在CellValidating或DataError事件中编制代码来检查输入的值是否正确。下面是实例代码:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
int newInteger;
dataGridView1.Rows[e.RowIndex].ErrorText = " ";
if ((dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "UnitsInStock ") ||
(dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "UnitsOnOrder ") ||
(dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "ReorderLevel "))
{
if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0)
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"Value must be a non-negative number ";
e.Cancel = true;
}
}
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = " ";
}
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "Invalid input. Please re-enter ";
e.Cancel = true;
}