Can data be kept in a dynamically bound GridView's invisible fields?

大兔子大兔子 提交于 2020-01-05 08:24:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!