user3267800
user3267800

Reputation: 29

delete rows in datagridview

I want to click the "chkCPTData" button to delete some rows of the datagridview "CPTData". I have hundreds of rows of data in the datagridview. The first time I click the button, no rows are deleted. Then I click another time, some of the rows are deleted. It takes me about 8 times to delete all rows I want to delete. How can I can delete the rows by clicking the button only once? Thanks!

  private void chkCPTData_Click(object sender, EventArgs e)
    {


        for (int rows = 0; rows <= CPTData.Rows.Count - 2; rows++)
        {
            double SampleDepth =(double)System.Convert.ToSingle(CPTData.Rows[rows].Cells[0].Value);
            if (SampleDepth > (double)System.Convert.ToSingle(analysisDepth.Text))
            {
                CPTData.Rows.RemoveAt(rows);
            }
        }

       CPTData.Refresh();


    }

Upvotes: 1

Views: 168

Answers (2)

Steve
Steve

Reputation: 216363

The problem is caused by the forward loop. In this way, when you delete a row the index rows points no more to the next row but to the row after the next.

For example, you are on rows=10 and you need to delete it, after that, the rows is incremented in the loop to 11 but at this point the offset 11 of the Rows array is occupied by the row that was at offset 12 before the delete. Effectively you are skipping a row in your check after every RemoveAt.

The usual way to solve it is to loop backward (starting from the end and going toward the first row)

private void chkCPTData_Click(object sender, EventArgs e)
{
    for (int rows = CPTData.Rows.Count - 1; rows >=0; rows--)
    {
        double SampleDepth =(double)System.Convert.ToSingle(CPTData.Rows[rows].Cells[0].Value);
        if (SampleDepth > (double)System.Convert.ToSingle(analysisDepth.Text))
        {
            CPTData.Rows.RemoveAt(rows);
        }
    }
    CPTData.Refresh();          

}

Upvotes: 1

LarsTech
LarsTech

Reputation: 81675

Deleting rows while enumerating through them will throw off the index, so try going in reverse instead:

for (int rows = CPTData.Rows.Count - 2; rows >=0; --rows)
{
  double SampleDepth =(double)System.Convert.ToSingle(CPTData.Rows[rows].Cells[0].Value);
  if (SampleDepth > (double)System.Convert.ToSingle(analysisDepth.Text))
  {
    CPTData.Rows.RemoveAt(rows);
  }
}

Upvotes: 1

Related Questions