我有一个来自数据表的 DataGridView。我试图阻止用户将非数字或负整数或双精度数输入到 datagridview 的不同列中。
我知道通常使用 CellValidating 方法,但我似乎无法让它捕获负值。
private void datagridview1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
string headerText = datagridview1.Columns[e.ColumnIndex].HeaderText;
// Abort validation if cell is not in the Age column.
if (!headerText.Equals("Quantity")) return;
int output;
// Confirm that the cell is an integer.
if (!int.TryParse(e.FormattedValue.ToString(), out output))
{
MessageBox.Show("Quantity must be numeric");
e.Cancel = true;
}
else if (output <= 0)
{
MessageBox.Show("Quantity must not be negative");
e.Cancel = true;
}
}
使用上面的代码,我仍然可以在数量单元格中输入负值甚至零值。
非常感谢帮助谢谢