简体   繁体   English

在C#Win表单中验证DataGridView

[英]Validating DataGridView in C# win form

I have a DataGridView that is sourced from a datatable. 我有一个源自数据表的DataGridView。 I'm trying to stop the user inputting non-numerical or negative integers or doubles into different columns from the datagridview. 我试图阻止用户在datagridview的不同列中输入非数字或负整数或双精度数。

I understand that a CellValidating method is commonly used but I can't seem to get it to capture negative values. 我知道通常使用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;
        }
    }

With the above code, I am still able to get negative or even zero values into the quantity cells. 使用上面的代码,我仍然能够将负值甚至零值添加到数量单元格中。

Help is much appreciated Thanks 非常感谢帮助,谢谢

I think you should place MessageBox code after Cancel the event. 我认为您应该在取消事件之后放置MessageBox代码。

Because when MessageBox pops up, it loses the focus from Cell , losing the focus will not let the event Cancel . 因为当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");
}

I think correct approach would be to make use of ErrorText property. 我认为正确的方法是利用ErrorText属性。

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

This gives clear indication like: 这给出了明确的指示,例如: 在此处输入图片说明

You can also use CellEndEdit event: 您还可以使用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;
        }

When Row Headers are not visible: 当行标题不可见时:

In that case, validation still works however error message and icon will not get displayed. 在这种情况下,验证仍然有效,但是不会显示错误消息和图标。 Use this approach with CellEndEdit even to get more control. 甚至可以将这种方法与CellEndEdit结合使用以获得更多控制权。 This will work even when row headers are not visible. 即使行标题不可见,这也将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM