hide Gridview Column but get value
i have a GridView which I databind it on Page_Load(). I want to hide one its columns but i want to still have access to it. I tried
SqlCommand sqlCommand = new SqlCommand("select name,surname,id from test", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataB开发者_如何学编程ind();
GridView1.columns[1].visible= False;
And i get the error Index was out of range. Must be non-negative and less than the size of the collection. Any ideas?
Use data keys for this.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" ...>
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Surname" DataField="Surname" />
</Columns>
</asp:GridView>
Once you add data keys, you can access the values like this:
//returns the id at the first row
int ID = GridView1.DataKeys[0]["ID"] as int;
have you checked this: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datacontrolfield.visible.aspx: "..add the field name to the DataKeyNames property of the data-bound control"
精彩评论