Gerie Tanabe
Gerie Tanabe

Reputation: 147

Restrict duplicate row in datagridview

I have Datagridview with the first column as combobox. How can I restrict the users to select only one item from the list. So if in the first row user has selected "Banana" already, in the second row the banana should not be allowed (perhaps displaying a message box saying, "banana already exist".

Thanks.

Upvotes: 0

Views: 2314

Answers (1)

David Hall
David Hall

Reputation: 33143

Here is a simple solution using the CellValidating event:

void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex == dataGridView1.Columns["MyCombo"].Index)
    {
        var query = from DataGridViewRow row in dataGridView1.Rows
                    where row.Cells[e.ColumnIndex].Value != null && row.Cells[e.ColumnIndex].Value.ToString() == e.FormattedValue.ToString()
                    where row.Index != e.RowIndex
                    select row;

        if (query.Any())
        {
            MessageBox.Show(string.Format("{0} already exists", e.FormattedValue.ToString()));
            e.Cancel = true;
        }
    }
}

This event triggers when the users tries to leave the cell containing the combo box - another option is to do something similar when the user leaves the current row using the RowValidating event.

Upvotes: 1

Related Questions