简体   繁体   中英

Validating DataGridView in C# win form

I have a DataGridView that is sourced from a datatable. I'm trying to stop the user inputting non-numerical or negative integers or doubles into different columns from the datagridview.

I understand that a CellValidating method is commonly used but I can't seem to get it to capture negative values.

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.

Because when MessageBox pops up, it loses the focus from Cell , losing the focus will not let the event 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.

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

This gives clear indication like: 在此处输入图片说明

You can also use CellEndEdit event:

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. This will work even when row headers are not visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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