一种选择是创建您自己的 CustomDataGridView 类,该类继承自DataGridView
类并覆盖适当的方法,如 KeyDown、ProcessDialogKey 等。
另一种选择是使用以下代码,这有点棘手。它的作用是强制用户插入有效数据。如果插入了无效值,当前单元格将被着色为红色,并返回编辑模式状态。在此示例中,我们假设无效值为"InavlidValue"
.
首先,添加这些字段(我们需要它们在不同的事件之间共享):
private bool colorCell = false;
private DataGridViewCell cell;
添加并附加这些事件:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
// Here we check for the invalid value, and store the cell position for later use
if (e.FormattedValue.ToString() == "InvalidValue")
{
colorCell = true;
cell = dataGridView1[e.ColumnIndex, e.RowIndex];
}
}
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
// When value is valid, change color back to normal
dataGridView1.CurrentCell.Style.BackColor = Color.White;
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
// User inserted invalid value, color the cell and return to edit mode
if (colorCell)
{
dataGridView1.CurrentCell = cell;
dataGridView1.CurrentCell.Style.BackColor = Color.Red;
dataGridView1.BeginEdit(true);
colorCell = false;
}
}