8

我有一个包含 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 中输入整数。由于我有一个列名称为“项目名称”,它应该作为文本输入,因此代码中存在问题。当我输入项目名称时,它会生成一条错误消息。其余的单元格验证工作正常!我应该如何编辑代码以使其不会产生此错误?

提前致谢

米尔法特

4

2 回答 2

9

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";
        }
    }
}
于 2013-01-05T14:48:28.700 回答
0

试试这个并想通了。

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (dataGridView1.IsCurrentCellDirty)
        {
            if (e.ColumnIndex == 0) //<-Column for String
            {
                Console.WriteLine(dataGridView1[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString());
                //Your Logic here
            }
            if (e.ColumnIndex == 1) //<-Column for Integer
            {
                Console.WriteLine(dataGridView1[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString());
                //Your Logic here
            }
        }
    }
于 2013-01-05T15:13:59.833 回答