Search code examples
c#asp.netwebformsaspxgridview

Show select gridview columns


I have a list of strings that I'm trying to use to control the columns shown in a gridview, but can't seem to figure out how to get it to work. Here's an example List<string> selectedHeaders = new List<string>(new string[] { "header1", "header2", "header3", "header4" });

How can I loop through the gridview columns and compare them to the values in selectedHeaders and set the visibility to false for all columns that don't match. Also note that the number of selectedHeaders can be different than the total number of columns within the gridview.

Here is what I have so far:

foreach (GridViewRow row in gvEmployees)
{
   for (int i = 0; i < gvEmployees.Columns.Count; i++)
   {
      if (gvEmployees.Column[i].HeaderText != selectedHeaders[i])
      {
         gvEmployees.Column[i].Visible = false;
      }
   }
}

I'm not sure how to refractor this it gives me an index out of range error, because the gridview has 6 columns, but selectedHeaders could contain 1-6 values.


Solution

  • Your loops don't make sense for what you're trying to accomplish.

    What you're doing: looping through every row in the GridView, and looping through every column within that, and looking for a string in your selectedHeaders with a matching index

    What you need to be doing: looping through every column, and checking to see if there's a corresponding record in selectedHeaders by value, not by index position.

    Change your code to this:

    for (int i = 0; i < gvEmployees.Columns.Count; i++)
    {
        if (!selectedHeaders.Any(h => h == gvEmployees.Column[i].HeaderText))
        {
            gvEmployees.Column[i].Visible = false;
        }
    }