Click here to Skip to main content
15,891,725 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a datagrid which contain a comobobox; combo box is Bound with a Data Source.
Now i want to prevent user to not select same combobox item more than one time in datagirdView.
i want to restrict him that he not selected same item in combobox of gridview.
Posted
Updated 16-May-14 4:26am
v2

sir, it is quite simple you have to loop through all previous rows where the value are saved and check if that value matches with the current selected value. If it matches then change the column index of the combobox.
 
Share this answer
 
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
C#
// using a loop through the DataGridView...
foreach (DataGridViewRow r in ((DataGridView)sender).Rows)
{
    if ((r.Cells["comboBoxColumn"].Value ?? "").ToString().Equals(e.FormattedValue.ToString()))
    {
        // Put your error message here
        e.Cancel = true;    // prevent the value being accepted
    }
}

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)
C#
// Using Linq...
IEnumerable<DataGridViewRow> rows = dataGridView1.Rows
        .Cast<DataGridViewRow>()
        .Where(r => (r.Cells["comboBoxColumn"].Value ?? "").ToString().Equals(e.FormattedValue.ToString()));
if (rows.Count() > 0)   // I.e. results were returned from the search
{
    // Put your error message here
    e.Cancel = true; // prevent the value being accepted
}

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
SQL
if (e.FormattedValue.ToString().Length > 0)
{ 
    ...
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900