WinForms DataGridView Behavior Similar to SQL Server Management Studio

I am working with a DataGridView in a Windows Form project. I would like to get something similar to what is added in edit mode in MS SQL Server Management Studio .

I am trying to explain: I have some required columns in my datagrid and I would like the row to be added to the grid only if the values ​​in these columns are valid. If the cell value is invalid, I would like to warn the user with the message field and press ESC , the invalid line should be discarded.

I tried using the CellValidating and RowValidating , but I am not satisfied with the result.

Can you help me?

UPDATE

I implemented RowValidating as follows:

 private void myGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e) { if (string.IsNullOrEmpty(myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].FormattedValue.ToString())) { e.Cancel = true; myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = "Mandatory"; MessageBox.Show("Error message"); } else { myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = string.Empty; } } 

If the value in the required field is invalid, the message box is displayed and the cell has a red dot, but pressing ESC I get an IndexOutOfRangeException ... An exception is IndexOutOfRangeException only if I show the message box, commenting on its method works (but this is not the behavior, which I want to achieve ...)

+4
source share
1 answer

This problem is explained in the following MSDN forums: Does DataGridView + RowValidating = Index 4 not matter?

This is basically an error (or at least a very unexpected behavior) in the way the DataGridView handles the check - MessageBox.Show () calls the check in a row that no longer exists.

I found that the following change to your code fixes the problem:

 private void myGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e) { // Note the check to see if the current row is dirty if (string.IsNullOrEmpty(myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].FormattedValue.ToString()) && myGrid.IsCurrentRowDirty) { e.Cancel = true; myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = "Mandatory"; MessageBox.Show("Error message"); } else { myGrid.Rows[e.RowIndex].Cells["MandatoryColumn"].ErrorText = string.Empty; } } 

The change is to check that the line being checked is dirty - when you press escape and delete the line, it no longer gets dirty, so this prevents an incorrect attempt to edit it.

+1
source

Source: https://habr.com/ru/post/1389443/


All Articles