0
votes

I need to delete the selected row from my DataGridView. Currently I managed to execute the select command but i do not know with what code to continue to remove/delete the selected row.

The code that i use is :

(refTofrPlanMain.dGVPlan.DataSource as DataTable).DefaultView.RowFilter = string.Format("Vodic = '{0}'", searchTBoxW.Text);
foreach (DataGridViewRow item in refTofrPlanMain.dGVPlan.Rows)
{
    if (item.Visible)
    {
        item.Selected = true;
        break;
    }
    //...
    //Other code
    //...
}

Where: - refTofrPlanMain represents a reference to Form1 (I am working in Form2) - dGVPlan is the DataGridView.

Thank you for your support.

1
Biggest problem is you're doing a foreach loop and should never delete during a foreach loop. Better to reverse iterate and delete like here: stackoverflow.com/questions/1582285/… - Draken
Thing is that i wil constantly search new values (the exact value will be filtered without doubles) and i want to delete it each time. Would that pose a problem ? - Stefan Siman
Not that I'm aware of, though I'm not sure I understand your question. The only issue you may have is the larger your list gets, the longer the time it takes to iterate. But you were iterating it anyway, so I don't see an issue - Draken
My question is what is the code to remove the selected row, that would fit my code above. - Stefan Siman
Check the posted answer, not 100% refTofrPlanMain.dGVPlan.Rows.Count is how you access the row count, but should be something similar - Draken

1 Answers

1
votes
(refTofrPlanMain.dGVPlan.DataSource as DataTable).DefaultView.RowFilter = string.Format("Vodic = '{0}'", searchTBoxW.Text);
for(int i=refTofrPlanMain.dGVPlan.Rows.Count-1; i >=0; i--)
{
    DataGridViewRow item = refTofrPlanMain.dGVPlan.Rows[i];
    if (item.Visible && !item.IsCurrentRowDirty())
    {
        refTofrPlanMain.dGVPlan.Rows.RemoveAt(i);
        break;
    }
    //...
    //Other code
    //...
}