首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

DataGridView中怎么控制其中一列只能输入数字

2012-03-09 
DataGridView中如何控制其中一列只能输入数字?DataGridView中如何控制其中一列只能输入数字?[解决办法]你

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

热点排行