Best way to validate data for DataGridView Combobox cell

Pat Hanks 81 Reputation points
2023-05-03T18:23:23.4333333+00:00

I am looking for the best approach for validating a combobox cell in a DataGridView. Background is this is a C# Windows Forms application with a datagridview used to define items for a recipe. There are 4 columns in the grid which 3 are combobox and 1 is a text cell. I need to check the selection of one column of comboboxs to prevent duplicate entires.

I have tried several events such as CellValidating, but by the time this is triggered the combobox has already been updated and a new row has been added. RowValidating does work to an extent, but same as CellValidating the row has already been added. Using the EditingControlShowing event seems the most promising but I ran into an issue where for some reason the color of the grid changes. I stepped through the code, but could not find where or what is causing this. I followed the example in this article to setup the events.

https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridviewcomboboxeditingcontrol?view=windowsdesktop-7.0

I used the SelectedIndexChanged event to call a method to verify the input. The verification is a simple foreach loop of all rows in the datagrid evaluating the FormattedValue of the column.


foreach (DataGridViewRow row in ComponentsDataGridView.Rows)
{
    if (row.Index != ComponentsDataGridView.CurrentRow.Index)
    {
        if ((string)row.Cells[ComponentsDataGridView.CurrentCell.OwningColumn.Index].FormattedValue == cmbText)
 { found = true; break; }
    }
}


C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,237 questions
{count} votes