Search code examples
c#asp.netlinqgridviewrowdatabound

Hide GridView Column using linq


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?


Solution

  • How about

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