今天在CSDN上看到有人问“如何取得GridView被隐藏列的值?”,当GridView列使用了Visible=false时,数据就不会被加载到表格中了,自然也取不到值了。但是我们就是想要取这个隐藏列的值该怎么办呢?我也遇到过这个问题, 印象中是设定GridView的DataKeys属性。网上搜了一下,总结一下基本有三种方法:
设置GridView列的Visible=false,再设定GridView的DataKeyNames="你想要隐藏的列ID"。例如:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1" >
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" Visible ="false" />
<asp:BoundField DataField="age" HeaderText="age" SortExpression="age" />
。。。
</Columns>
</asp:GridView>
方法二:
设置一个Css类:
.hidden { display:none;}
随后在GridView的列编辑对话框中,对需要进行隐藏的列进行设置,分别设置FootStyle,HeaderStyle,ItemStyle的CssClass属性为“hidden” Ok,这样我们就实现了隐藏列的目的,同时又能保证对其进行数据绑定。
方法三:
在GridView中设置该列的Visible为True,然后在RowCreated事件中设置隐藏,这样就能取到隐藏列的值了。例如:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[1].Visible = false;
}
}