Consider a DataGridView
whose DataSource
is a DataTable
. The dataGridView allows one row to be selected at a time. There is a "delete" button, which should delete the selected rows, by one of the columns, from the bound dataTable.
I have configured the DataGridView
to be uneditable, from the user's point of view. It should only be possible to delete a row (from the dataTable and the grid) via a separate "delete" Button
I have created. The event handler for this is shown below:
private void delete_Click(object sender, EventArgs args)
{
var usersTable = myGridView.DataSource as DataTable;
foreach (DataGridViewRow selected in myGridView.SelectedRows)
{
string name = (string)selectedRow.Cells[0].Value;
foreach (DataRow tableRow in usersTable.Rows)
{
if (tableRow["Name"].ToString().Equals(name))
tableRow.Delete();
}
usersTable.AcceptChanges();
}
myGridView.DataSource = usersTable;
}
How to does this properly, without "collection was modified, enumeration might not execute" errors?
The grid is being populated as follows:
private DataTable usersTable = new DataTable("Users");
void Populate()
{
usersTable.Columns.Clear();
usersTable.Rows.Clear();
usersTable.Columns.Add("Name", typeof(string));
// addd other columns...
foreach (var user in usersCollection)
{
usersTable.Rows.Add(user.GetName()),
// add other rows...
}
// bind the data
myGridView.DataSource = usersTable;
}
DataGridView
will allow the user to simply press theDelete
key to delete the selected row. No code required. – Ňɏssa PøngjǣrdenlarpDataTable
be affected by this, though? That is the important part. – Al2110Delete
key, corresponding row(s) also will be deleted from the DataTable which is bound to the GridView. – ChetanDataGridView
to be uneditable from the user's point of view. So, the only way to delete a row from the table is programmatically. I have tried to achieve this by adding a separate "delete"Button
, whose click event handler has the code above. Clicking the button throws a "collection was modified; enumeration might not execute". I want to be able to remove the selected row from theDataTable
, then re-bind it to theDataGridView
. – Al2110