I have a datagridview on a windows form and I want to be able to delete all rows that have a negative or zero value within a specific column (when user presses button), but I don't know the best way to approach this.
dataGridView2 example:
1 48.54 Col 3 Ref
2 78.14 Col 3 Ref
3 -148.52 Col 3 Ref
4 486.45 Col 3 Ref
Could someone provide assistance on the best way to do this?
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
if (double.Parse(dataGridView2.Rows[i].Cells[1].Value.ToString()) < 0)
{
//What do I need to delete row?
i = i -1;
}
}
}
Loading
AlanPosted Jul 29, 2008, 11:49 AM
You need to iterate through the Rows collection backwards (so as not to interfere with the indices still to be examined) and then use the RemoveAt() method:
private void button1_Click(object sender, EventArgs e)
{
for (int i = dataGridView2.Rows.Count - 1; i >=0 ; i--)
{
if (dataGridView2.Rows[i] == null) continue;
if (double.Parse(dataGridView2.Rows[i].Cells[1].Value.ToString()) <= 0)
{
dataGridView.Rows.RemoveAt(i);
}
}
}