Further to Solution 1 ...
You should loop through
all rows on the DataGridView because Users are not obliged to enter data in the order you think they ought to! ;-)
The validation should go into the
CellValidating
event.
As Agent_Spock suggested, one way of doing it is to use a
foreach
loop like this
foreach (DataGridViewRow r in ((DataGridView)sender).Rows)
{
if ((r.Cells["comboBoxColumn"].Value ?? "").ToString().Equals(e.FormattedValue.ToString()))
{
e.Cancel = true;
}
}
However, now I'm starting to use Linq more and more, I prefer this search instead (but you've tagged C#3.5 so may not be able to do this)
IEnumerable<DataGridViewRow> rows = dataGridView1.Rows
.Cast<DataGridViewRow>()
.Where(r => (r.Cells["comboBoxColumn"].Value ?? "").ToString().Equals(e.FormattedValue.ToString()));
if (rows.Count() > 0)
{
e.Cancel = true;
}
Note that you will need to change
"comboBoxColumn"
to the name of your column containing the comboBoxes and you will need
using System.Linq;
if you use the Linq method.
Notice the
(r.Cells["comboBoxColumn"].Value ?? "").ToString()
If you attempt to access the
Value
of a cell that has nothing in it, you will get a
NullReferenceException
Quote:
Object reference not set to an instance of an object.
The
??
is the
null-coalescing operator[
^] - in this case I'm using an empty string to avoid the exception.
Finally, this event can get fired before the User has selected anything from the list (e.g. they click on it but change their mind) so I surrounded my validation with
if (e.FormattedValue.ToString().Length > 0)
{
...
}