日期:2014-05-19  浏览次数:20740 次

DataGridView中如何控制其中一列只能输入数字?
DataGridView中如何控制其中一列只能输入数字?

------解决方案--------------------
你可以在如下事件里对输入进行验证并可取消输入:

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 ";
}
}