如何在GridView中获取主键但不显示它?

Rah*_*man 6 c# asp.net gridview

使用<asp:GridView></asp:GridView>我试图显示数据库表的列.我想获取表的主键但显然不想显示它.我怎样才能做到这一点?
这是我的GridView

<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF" AllowPaging="false" PageSize="5" AllowSorting="true" AutoGenerateColumns="false"
         AutoGenerateEditButton="true" OnRowEditing="MyGrid_RowEditing" AutoGenerateDeleteButton="true" OnRowDeleting="MyGrid_RowDeleting"
         OnRowDataBound="MyGrid_RowDataBound" EmptyDataText="No Value" BorderWidth="0px" BorderStyle="Solid">
    <Columns>
        <asp:BoundField DataField="PrimaryKey" HeaderText="UserId"/>
        <asp:BoundField DataField="Column1" HeaderText="Column1" />
        <asp:BoundField DataField="Column2" HeaderText="Column2" />
        <asp:BoundField DataField="Column3" HeaderText="Column3" />
    </Columns>
</asp:GridView>  
Run Code Online (Sandbox Code Playgroud)

我也试图visible=false隐藏主键,它隐藏了主键,但也没有获取它的值,我想要这个值.
希望我的问题很明确.

Chr*_*s L 6

您需要在OnRowDataBound事件中设置Visible = false ,这意味着您仍然可以访问数据,但不会在页面上显示.

<asp:GridView ID="MyGrid" runat="server" BorderColor="#0066FF" 
    AllowPaging="false" PageSize="5" AllowSorting="true" 
    AutoGenerateColumns="false" AutoGenerateEditButton="true"      
    OnRowEditing="MyGrid_RowEditing" AutoGenerateDeleteButton="true" 
    OnRowDeleting="MyGrid_RowDeleting"
    OnRowDataBound="MyGrid_RowDataBound" EmptyDataText="No Value" 
    BorderWidth="0px" BorderStyle="Solid">
    <Columns>
        <asp:BoundField DataField="PrimaryKey" HeaderText="UserId"/>
        <asp:BoundField DataField="Column1" HeaderText="Column1" />
        <asp:BoundField DataField="Column2" HeaderText="Column2" />
        <asp:BoundField DataField="Column3" HeaderText="Column3" />
    </Columns>
</asp:GridView>
Run Code Online (Sandbox Code Playgroud)

在Codebehind中:

protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[0].Visible = false;
}
Run Code Online (Sandbox Code Playgroud)