你可以在如下事件里对输入进行验证并可取消输入:DataGridView.CellValidating 事件 在单元格失去输入焦点时发生,并启用内容验证功能。 比如下面的代码: 下面的代码示例处理 CellValidating 事件,以确保用户仅输入正整数。此示例摘自 VirtualMode 参考主题中提供的一个更大示例。private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { dataGridView1.Rows[e.RowIndex].ErrorText = ""; int newInteger; // Don't try to validate the 'new row' until finished // editing since there // is not any point in validating its initial value. if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; } if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0) { e.Cancel = true; dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a non-negative integer"; } }
在单元格失去输入焦点时发生,并启用内容验证功能。 比如下面的代码:
下面的代码示例处理 CellValidating 事件,以确保用户仅输入正整数。此示例摘自 VirtualMode 参考主题中提供的一个更大示例。private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int newInteger; // Don't try to validate the 'new row' until finished
// editing since there
// is not any point in validating its initial value.
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
if (!int.TryParse(e.FormattedValue.ToString(),
out newInteger) || newInteger < 0)
{
e.Cancel = true;
dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a non-negative integer";
}
}
且对一个单元格来说,它的按键及鼠标处理基本上都要在列的编辑控件上操作。
除非你自定义DataGridView的列了。