Getting the value of an invisible column on row bound in a GridView
I have an ASP.NET GridView control in a Web Form. For the sake of simplicity, I will say that this GridView is defined as follows:
<asp:GridView ID="myGridView" runat="server" AutoGenerateColumns="false"
AllowPaging="true" AllowSorting="true" PageSize="50"
OnRowDataBound="myGridView_RowBound" DataKeyNames="I开发者_高级运维D"
OnLoad="myGridView_Load" OnPageIndexChanging="myGridView_PageIndexChanging"
OnSorting="myGridView_Sorting">
<Columns>
<asp:BoundField DataField="ID" Visible="false" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
</Columns>
</asp:GridView>
When each of these rows is bound (a.k.a. during the "myGridView_RowBound" event), I want to get the ID, Name, and Age values. My problem is, I cannot figure out how to get the "ID" value. The reason why is because it is in an invisible field. Can someone tell me how to get the value
You can either hide the cell after the data is bound (onrowcreated) or deal with the binding to hide the column.
Check this article for more info.
On your row data bound event you can get access to the ID via the bound data item. There is no need to interact with the columns.
For example in the row data bound event you might have.
void myGridView_RowBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as T;
// where T is your item type
if (item != null) {
var id = item.ID;
}
}
}
精彩评论