1

I have a GridView in which I have added additional HeaderRows at various points to give the illusion of different sections to the GridView. The problem that I am having is that when I perform a postback the HeaderRows that I created turn into blank rows. I am able to add additional HeaderRows again but I then face the problem of the blank rows "bumping" the data into the incorrect "sections."

What I would like to do is, on postback, call a function that runs through the GridView and removes the blank rows/old HeaderRows and then call the function that added the HeaderRows in the first place.

I need help with the function to remove the rows. The code that I have right now for the function is:

protected void removeBlankRows()
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        if (row.Cells[6].Text == "")
        {
            //-->code to remove blank row here<--
        }
    }
} 
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
arcaderob
  • 481
  • 1
  • 7
  • 21

3 Answers3

0
protected void removeBlankRows()
{
    for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    string strtrial = Convert.Tostring(row.Cells[6].Text);
                     if(string.IsNullOrEmpty(strtrial ))
                     GridView1.DeleteRow(i);
                }
            }

However it will be better if you remove those rows in Rowbound event.

Suraj Singh
  • 4,041
  • 1
  • 21
  • 36
  • I would advise against modifying a collection while iterating. Even if it works in this case, you're asking for trouble when you get into this habit. – priehl Aug 27 '13 at 16:32
  • @priehl I'll take the advice but can you please elaborate more ,all i think of now is concurrent transactions ,which seems not going to be a issue here(am i right?) . A good tip is always welcome , Thanks ! – Suraj Singh Aug 29 '13 at 07:32
0
var blanks = GridView1.Rows
    .Where( e => string.IsNullOrEmpty(e.Cells[6].Text))
    .Select(e => e.RowIndex);

foreach(var blank in blanks)
    GridView1.DeleteRow(blank);
priehl
  • 644
  • 2
  • 9
  • 21
0

Why not to just hide the row?

private void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
 {
    if (e.Row.Cells[6].Text == "") 
        e.Row.Visible = false;
 }

Also, why you don't hide your records on databinding event rather than iterating through rows?

smiling4ever
  • 152
  • 1