C#中Datagridview单元格值的验证

前端之家收集整理的这篇文章主要介绍了C#中Datagridview单元格值的验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含datgridview的 Windows窗体应用程序.我需要在datagridview单元格上强制执行单元格验证,以便它不接受负值.我从msdn库中找到了合适的代码.
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 Positive integer";
}
}

不幸的是,代码只允许在datagridview中输入整数.由于我的列名称为“项目名称”,应该作为文本输入,因此代码中存在问题.当我输入项目名称时,它会生成一条错误消息.其余的单元格验证完全正常工作!我该怎么编辑代码,以免它产生这个错误

提前致谢

Mirfath

解决方法

DataGridViewCellValidatingEventArgs e具有.ColumnIndex属性,您可以检查该属性以确保仅对您希望的列进行验证.
private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e) {
    if (e.ColumnIndex == dataGridView1.Columns["MyNumericColumnName"].Index) {
        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 Positive integer";
        }
    }
}

猜你在找的C#相关文章