简体   繁体   中英

DataGridView Column Allow Only Unique Values

I have a DataGridView which is bound to a BindingSource populated from database .

The database field "UnitNumber" will always be a value between 1 and 30 even if I have a million rows - not unique.

Another related field a Foreign Key "RelateID" basically forms a subset of rows - which can only have unique UnitNumbers 1 to 30.

So in my DataGridViewColumn representing UnitNumber - I desire that it could be Unique Constrained so Entry in other words if I have UnitNumbers 1 to 20 in the DataGridView already and the User adds a row - I do not want them to be able to add UnitNumber 14 again - a duplicate of what is already in the Column and for the Rows.

How can I ensure that the user only enters a valid UnitNumber that does not already exist in the DataGridView Column UnitNUmber ?

I have read about setting a Unique Constraint on the Data Column of the Bindingsource this fails with these columns don't currently have unique values and I know what the error is telling me - it refers to the underlying data source - how can I force a constraint on my DataGridViewColumn with out forcing one on the underlying Data Source ?

I have also read about the cell validating event ; but not sure if it is the correct place to do it, if I use property changed update mode will that be a problem , Cell Validated update mode I think that will work.

What implementation should I use to accomplish a unique constraint on the DataGridView column with out affecting the underlying DataSource .

There's no automatic way of doing it. You would have to handle the CellValidating event of the grid, get the combination of those values for the current row and then loop through the grid rows to determine whether that combination was already present, failing validation if it was. By failing validation, ie setting e.Cancel to True , you prevent the user leaving that cell until they enter a valid value.

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