1

我有一个来自数据表的 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;
        }
    }

使用上面的代码,我仍然可以在数量单元格中输入负值甚至零值。

非常感谢帮助谢谢

4

2 回答 2

1

我认为您应该在取消事件MessageBox之后放置代码。

因为当MessageBox弹出时,它会失去焦点Cell,失去焦点不会让事件发生Cancel

// Confirm that the cell is an integer.
if (!int.TryParse(e.FormattedValue.ToString(), out output))
{                
        e.Cancel = true;
        MessageBox.Show("Quantity must be numeric");
}
else if (output <= 0)
{            
    e.Cancel = true;
    MessageBox.Show("Quantity must not be negative");
}
于 2015-05-08T05:33:11.367 回答
1

我认为正确的方法是使用 ErrorText 属性。

dataGridView1.Rows[e.RowIndex].ErrorText = "Quantity must not be negative";

这给出了明确的指示,例如: 在此处输入图像描述

您还可以使用 CellEndEdit 事件:

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // Clear the row error in case the user presses ESC.   
            dataGridView1.Rows[e.RowIndex].ErrorText = string.Empty;
        }

当行标题不可见时:

在这种情况下,验证仍然有效,但不会显示错误消息和图标。将此方法与 CellEndEdit 一起使用甚至可以获得更多控制。即使行标题不可见,这也会起作用。

于 2015-05-08T05:50:14.810 回答