0

I have a DataSet called EventDBDataSet and there is a DataTable called Contacts in it. I'm trying to delete a row from the DataTable and it's not working and it does not throw any errors. I tried some of the Stack Overflow solutions regarding this, but none of them worked for me. Following the code for deleting the row from DataTable

public void deleteContact(Int16 contactId)
{
    EventDBDataSet eventDBDataSet = new EventDBDataSet();
    EventDBDataSetTableAdapters.ContactsTableAdapter contactsTableAdapter =
        new EventDBDataSetTableAdapters.ContactsTableAdapter();

    contactsTableAdapter.Fill(eventDBDataSet.Contacts);

    EventDBDataSet.ContactsRow contactsRow = eventDBDataSet.Contacts.FindBycontactId(contactId);

    eventDBDataSet.Contacts.RemoveContactsRow(contactsRow);

    eventDBDataSet.Contacts.AcceptChanges();

    contactsTableAdapter.Update(eventDBDataSet.Contacts);

}

what I'm missing here?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

0

If you delete an item from a collection, that collection has been changed and you can't continue to enumerate through it.

Instead, use a For loop, such as:

public void RemoveRow()
    {
        DataTable dt = new DataTable();

        foreach (var row in dt.Select())
        {
            if (row["ID"].ToString().Equals("NAME"))
            {
                dt.Rows.Remove(row);
                dt.AcceptChanges();
            }
        }
    }
Ash Peterson
  • 26
  • 1
  • 10