I have a datagridview that displays data from an XML file. The DGV is called TaskTable.
I have a checkbox in each row and a button that should delete any row that has a checkbox selected in.
However, at the moment I can only get one row to be deleted at a time when I need multiple rows to be deleted if multiple rows are selected from both the DGV and the back end XML file.
Here is the code that is successfully deleting one row at a time:
private void RemoveButton_Click_1(object sender, EventArgs e) // removes checked tasks.
{
int i = 0;
{
for (i = 0; i <= TaskTable.Rows.Count - 1; i++)
{
if (TaskTable.Rows[i].Cells[0].Value != null)
{
if ((bool)TaskTable.Rows[i].Cells[0].Value == true)
{
if (MessageBox.Show("Are you sure you want to remove the selected task?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) // confirmation
{
TaskTable.Rows.RemoveAt(i); //Here If Checkbox Selected Then It Will Delete The Row From The GridView
}
}
}
}
}
TaskDataSet.WriteXml(fileURL);
TaskDataSet.AcceptChanges(); // re writes xml file and removes deleted tasks.
}
Please help me to amend my code, allowing me to delete multiple tasks at one time.
The following code should work. It builds a list of rows to delete, asks for confirmation, and then deletes the selected rows.
The deletions must be done in order of descending row index to prevent the deletions from changing the row indexes or rows that still need deleting.