I have a GridView with BoundColumns. The first 2 columns are hidden and I would like to access them using gridView1.Rows[0].Cells[0].Text and gridView1.Rows[0].Cells[1].Text respectively and I get a empty string. When the columns are changed to visible, then I can access the values. I have tried changing the column width to zero as suggested on some other forums but that never fixed the problem. Does any one have any pointers as to what I may be doing wrong.
3 Answers
If the Columns are part of the DataKeyNames
collection, then you should get their values from the GridView.DataKeys[index].value
property, as demonstrated on the GridViewGuy site.
If however, they are not part of the DataKeyNames
collection, then you can use the following hack to make sure that the value is persisted in ViewState (as opposed to normal behaviour for hidden fields in ASP.NET 2+)
GridView1.DataSource = myDataSource;
// Set the column visibility to true before Databinding
GridView1.Columns[0].Visible = true;
GridView1.Columns[1].Visible = true;
GridView1.DataBind()
// Set the column visibility to false after Databinding
GridView1.Columns[0].Visible = false;
GridView1.Columns[1].Visible = false;

- 25,615
- 8
- 56
- 70
Add the css class hiddencol
to the column you want to hide. Add hiddencol
class to your css and you're good to go.
You can still access the column in your code behind but it isn't displayed on your page.
<asp:BoundField DataField="Site_ID" ItemStyle-CssClass="hiddencol" />
.hiddencol
{
display: none;
}

- 7,043
- 3
- 29
- 47

- 11
- 1
This is typical behaviour in ASP.NET, Visible = false, only makes the control available in code-behind.
The best for this would be to apply the following style on that column:
display:'none'

- 115,091
- 17
- 196
- 297
-
Given that it's rendered as a table in html, which is row oriented, can you set a display:none style on a column? I'm not saying you can't, I just have never tried it! Would it render the display:none style on each td cell in the column? – Andrew Rollings Mar 12 '09 at 13:50
-
Now that you mention it, I wonder... it will probably place the style on the TD, not sure if that will work. Thanks :) – leppie Mar 12 '09 at 13:57