2

I have following code to hide column and edit column header. But its not going into foreach. I have tried various method by putting the foreach into DataBound, RowDataBound, RowCreated events. But not working.

GridView1.AutoGenerateColumns = true;
GridView1.DataSource = SomeObject[];
GridView1.DataBind();

foreach (DataControlField col in GridView1.Columns)
{
    if (col.HeaderText == "FirstName") 
    {
        col.HeaderText = "First Name"; 
    }
    if (col.HeaderText == "SchoolName") 
    { 
        col.Visible = false; 
    }
}

Can anyone please advice me the fix. Thanks

Xaruth
  • 4,034
  • 3
  • 19
  • 26
user1211185
  • 731
  • 3
  • 12
  • 27

5 Answers5

1

Note that columnss count would be 0 when you do AutoGenereateColumns = true

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[index].Visible = false;
}

to set a column invisible using the GridView's RowDataBound event.

On aspx page you can declare in gridview control like this

<asp:GridView runat="server" OnRowDataBound="GridView_RowDataBound" .../>
Dusht
  • 4,712
  • 3
  • 18
  • 24
1

Try this instead:

int indexOfSchoolName = -1;
int columnIndex = -1;
foreach(TableCell cell in GridView1.HeaderRow.Cells)
{
    columnIndex ++;
    if (cell.Text == "FirstName") 
    { 
        cell.Text = "First Name"; 
    }
    if(cell.Text == "SchoolName") indexOfSchoolName = columnIndex;
} 
if(indexOfSchoolName != -1)
{
    foreach(GridViewRow row in GridView1.Rows)
    {
        row.Cells[indexOfSchoolName].Visible = false;
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Why do you not remove the column from SomeObject[] or clone it and then remove the column?

Fabrizio A
  • 3,072
  • 5
  • 24
  • 35
0

If SomeObject[] is an array then you may have to try to make a copy of SomeObject[] to say CopyObject[] and manipulate this array to exclude the column that you want. Finally rebind it to your grid view.

Nisha
  • 1,379
  • 16
  • 28
0

I normally do something like this:

private int GetColumnIndexByName(GridView grid, string name)
{
    foreach (DataControlField col in grid.Columns)
    {
        if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())
        {
            return grid.Columns.IndexOf(col);
        }
    }

    return -1;
}

GridView1.Columns[GetColumnIndexByName(GridView1, "SchoolName")].Visible = false;
Bit
  • 1,068
  • 1
  • 11
  • 20