0

I am trying to hide my gridview columns on RowDataBound event. At the moment, I am doing :

e.Row.Cells[4].Visible = false;

The problem with this approach is that whenever I change the order of the column in grid veiw, I also have to change the index here.

Also, there is another approach :

foreach (TableCell col in e.Row.Cells)
        {
            if (col.Text == "Name")
            {
                col.Visible = false;
            }
        }

I was told by someone that it is possible using the LINQ.

Something like:

((TableCell)e.Row.Cells.Cast<TableCell>()
             .Where(c => c.Text == "name")).Visible = false;

So far, I am unable to do so. Can someone tell me what I am doing wrong here?

Usman Khalid
  • 3,032
  • 9
  • 41
  • 66

2 Answers2

3

How about

e.Row.Cells.Cast<TableCell>()
           .Where(c => c.Text == "name")
           .ToList()
           .ForEach(col => col.Visible = false);
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
1

In case anyone else find this. I modified Nikhil's answer to hide the entire column (inluding the Header).

e.Row.Cells.Cast<DataControlFieldCell>()
    .Where(c => c.ContainingField.HeaderText == "Name" 
             || c.ContainingField.HeaderText == "Title")
    .ToList()
    .ForEach(c => c.ContainingField.Visible = false);
Sam Banks
  • 85
  • 13