2
votes

I have datagridview on my winform. I am displaying records in the datagridview. Now after displaying the records on the datagridview, I want to remove the row from datagridview which has one or more empy cells that is no value in the cell for that row. So for that I am checking each cell for every row if there is any cell empty or null then I remove that rows using RemoveAt() function.

My code is :

for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    if (string.IsNullOrEmpty(dataGridView1.Rows[i].Cells[j].Value.ToString()))
                    {
                        dataGridView1.Rows.RemoveAt(i);
                        break;
                    }
                }
            }

Then problem is it does not work properly that it does not remove all the rows which has empty cell. So what should I do here ?

1
You are not asking a question here. Closing as not a real question. - Oded
@Oded,Sorry Sir,I don't understand.Why it is going to be closed ? - Harikrishna
@Oded - It is pretty clear to me what the question is. The OP wants to remove more than one row from a datagrid view. - David Hall
@David Hall - The question has been edited and that was added later one. - Oded
Do you want to remove the row just from the DataGridView (so it's gone from sight), or from the DataSource (so that it's really gone)? - SeaDrive

1 Answers

4
votes

The simplest way to do what you want is to loop through the datagridview rows in reverse. This way your indices stay correct.

for (int i = dataGridView1.Rows.Count -1; i >= 0; i--)
{
    DataGridViewRow dataGridViewRow = dataGridView1.Rows[i];

    foreach (DataGridViewCell cell in dataGridViewRow.Cells)
    {
        string val = cell.Value as string;
        if (string.IsNullOrEmpty(val))
        {
            if (!dataGridViewRow.IsNewRow)
            {
                dataGridView1.Rows.Remove(dataGridViewRow);
                break;
            }
        }            
    }
}

I'm doing a couple of extra things that you may not need to do (the code is just cut and pasted from my test application)

  • I usually grab the row in question into a DataGridViewRow object.
  • I am checking the IsNewRow property because my grid was editable.
  • I am assigning the value to a string variable (with an as to cast it) since the way you had it was throwing an exception for me.