An incomprehensible situation occurred when deleting data from their dataGridView

if (dataGridView4.Rows.Count > 0) { this.Invoke(new Action(() => dataGridView4.Rows.Clear())); } for (int i = 0; i < Count; i++) { this.Invoke(new Action(() => dataGridView4.Rows.Add())); this.Invoke(new Action(() => dataGridView4.Rows[0].Visible = false)); this.Invoke(new Action(() => dataGridView4.Rows[i].Cells[0].Value = imageList2.Images[39])); } 

when you try to add them again displays a message on

 this.Invoke(new Action(() => dataGridView4.Rows.Add())); 

Object reference not set to an instance of the object.

and if you do so

 this.Invoke(new Action(() => listBox1.Items.Clear())); if (dataGridView4.Rows.Count > 0) { for (int i = 1; i < dataGridView4.Rows.Count; i++) { this.Invoke(new Action(() => dataGridView4.Rows.RemoveAt(i))); } //this.Invoke(new Action(() => dataGridView4.Rows.Clear())); } for (int i = 0; i < Count; i++) { this.Invoke(new Action(() => dataGridView4.Rows.Add())); this.Invoke(new Action(() => dataGridView4.Rows[0].Visible = false)); this.Invoke(new Action(() => dataGridView4.Rows[i].Cells[0].Value = imageList2.Images[39])); } 

then it only deletes part of the data.

    2 answers 2

    Try writing this:

     public static class DataGridViewEx { public static void ClearRows(this DataGridView dataGridView) { if (dataGridView.DataSource != null) { dataGridView.DataSource = null; } else { dataGridView.Rows.Clear(); } dataGridView.Refresh(); } } 

    Call:

     dataGridView4.ClearRows(); 

      Replace:

       for (int i = 1; i < dataGridView4.Rows.Count; i++){ this.Invoke(new Action(() => dataGridView4.Rows.RemoveAt(i))); } 

      on

       for (int i = dataGridView4.Rows.Count - 1; i >= 0; --i){ this.Invoke(new Action(() => dataGridView4.Rows.RemoveAt(i))); } 

      The problem can be easily understood if you manually run your cycle on a piece of paper.

      Run through the steps:

      1. i = 1; Count, suppose 5. 1 <5; Remove 1 item.
      2. i = 2; Count = 4; 2 <4, Remove 2 item.
      3. i = 3; Count = 3; 3 = 3; We do not delete anything.

      As a result, the 1st and 3rd elements retired. You may ask: "Why is the 3 element?". Because at step 1 we deleted the element, so at step 2 when removing 2 elements (deleting something from the new array of strings), in fact 3 elements of the initial array of strings are deleted.

      • Yes, I already noticed this error, but I would like to use dataGridView4.Rows.Clear () - SergD29