Dilukshan Mahendra
Dilukshan Mahendra

Reputation: 3398

Delete rows which has a specific value from DataGridView C#

I have a WinForm DataGridView as follows where I need to delete rows which having a specific value in a column

enter image description here

In this case I'm using a textfield to type Code and after clicking "Delete" all the rows which having ITM-000001 under column value. I have no clue where to start.

private void deleteClick(object sender, EventArgs e)
{      
    String code = txtCode.Text;
    // CODE HERE       
}

Upvotes: 3

Views: 9062

Answers (3)

Ramin Morsali
Ramin Morsali

Reputation: 1

in a button or other event you can enter:

foreach (DataGridViewRow row in dataGridView1.Rows)
if (convert.toString(row.Cells[0].Value) == "ITM-000001")
    dataGridView1.Rows.RemoveAt(row.Index);

Upvotes: 0

TaW
TaW

Reputation: 54433

Not necessarily better or even simpler than Matthew's solution; just a different approach I sometimes find useful:

    List<DataGridViewRow> RowsToDelete = new List<DataGridViewRow>();
    foreach (DataGridViewRow row in dataGridView1.Rows)
        if ( row.Cells[0].Value != null && 
             row.Cells[0].Value.ToString() == "TTTT") RowsToDelete.Add(row);
    foreach (DataGridViewRow row in RowsToDelete) dataGridView1.Rows.Remove(row);
    RowsToDelete.Clear();

This way you could use the list as a buffer after or give the number of hits before actually deleting them.

I also liked his use of string.Equals and do it differently here just for fun..

Upvotes: 3

Matthew Haugen
Matthew Haugen

Reputation: 13286

It's been a long while since I did anything with Windows Forms (oh, the good ol' days), so excuse me if this is a little off, but you should be able to accomplish this with something like...

for(int v = 0; v < dataGrid1.Rows.Count; v++)
{
    if(string.Equals(dataGrid1[0, v].Value as string, "ITM-000001"))
    {
        dataGrid1.Rows.RemoveAt(v);
        v--; // this just got messy. But you see my point.
    }
}

Upvotes: 3

Related Questions