Nathan F.
Nathan F.

Reputation: 3469

No Duplicates in DataGridView

I'm working in C# displaying some data in a DataGridView and I'd like it to not allow you to add a duplicate key.. Right now, my DataGridview is pretty simple with just 2 columns. One is called "Key" the other is called "Value". What i want, is for when the user edits or adds a new entry to the DataGridView, it checks if there is already a duplicate and cancels the edit/creation of the new row. Here is my current code:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.Cells[0].Value.Equals(dataGridView1.Rows[e.RowIndex].Cells[0].Value))
        {
            dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
            break;
        }
    }

    refresh();
}

It isn't working at all... Can someone tell me how I should be doing this?.. Thanks!

Edit: I'm also getting this error on the dataGridView1.Rows.Remove() call -

Operation is not valid because it results in a reentrant call to the  SetCurrentCellAddressCore function.

Edit:

The DataGridView looks like this

Key     | Value 
----------------
blah    | something 
somekey | somevalue

Upvotes: 3

Views: 5544

Answers (3)

ketan italiya
ketan italiya

Reputation: 296

try with this code for that,

protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
     DataTable dt1 = ViewState["dt"] as DataTable;
     if (e.CommandName == "Add")
     {
DataRow dr;
          dr = dt1.NewRow();
dr["DED_Id"] = Material_Id;
          dr["DED_Name"] = Material;
          dt1.Rows.Add(dr);
          dt1.AcceptChanges();
          ViewState["dt"] = dt1;
     }
}

Upvotes: 0

IssamTP
IssamTP

Reputation: 2440

I'm only guessing but I've tried your code and I've seen a logical error: if you debug it you'll see that with the foreach loop you'll necessary hit the element you just edited, which is obviously equal to itself.

I suggest you to change the loop to a for or to check if the row index is the same.

Upvotes: 0

user153923
user153923

Reputation:

It is probably your foreach loop, which doesn't allow deleting rows.

Try something like this:

private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
  for (int i = 0; i < DataGridView1.Rows.Count; i++) {
    DataGridViewRow row = DataGridView1.Rows[i];
    if (row.Cells[0].Value == DataGridView1.Rows[e.RowIndex].Cells[0].Value) {
      DataGridView1.Rows.RemoveAt(e.RowIndex);
      DataGridView1.FirstDisplayedScrollingRowIndex = i;
      return;
    }
  }
}

I do not allow row editing, though, so I could be wrong.

EDIT: Just a quick edit. I'd set the FirstDisplayedScrollingRowIndex to e.RowIndex, but that row would have just been deleted!

Upvotes: 1

Related Questions