问题
I have a query expression which I am binding to a GridView in Page_Load. The data I want to capture in the SelectedIndexChaned event is in a BoundField defined thus:
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"
SortExpression="ID" Visible="False" />
If I set Visible="True", I have no trouble getting this data. Is there a way to hide the ID field and still get the data?
回答1:
Depends on how you are trying to get the data. If this is an ID field that is unique for each row in the datasource, use DataKeyNames = "ID" in the GridView declaration. Then, in the code behind, whenever you need the ID, you can use the following line:
string ID = GridView1.Rows[GridRowIndex].DataKeys[0].Value.ToString();
You could also convert one of your BoundFields to a TemplateField, and place a HiddenField in it to store the ID. Like so:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="someOtherDataLabel" runat="server" />
<asp:HiddenField ID="IDHiddenField" runat=server />
</ItemTemplate>
</asp:TemplateField>
Then you could use FindControl() in the RowDataBound event of the GridView to store the ID value.
来源:https://stackoverflow.com/questions/4195852/can-data-be-kept-in-a-dynamically-bound-gridviews-invisible-fields