开发者

How to remove row which has one or more empty or null cell?

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 ?


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜