How to fetch primary key in GridView but don't display it?
asp.net, c#, gridview
Solution
You need to set Visible = false within the OnRowDataBound event, this will mean the data is still accessible to you, but won't display on the page.
<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>
In Codebehind:
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false;
}
Problem
Using `<asp:GridView></asp:GridView>` I am trying to display columns of database table. I want to fetch primary key of table but obviously don't want to display it. How can I achieve this? This is my 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> ``` I also tried `visible=false` to hide primary key, it hides primary key from displaying but also don't fetch its value and I want this value. Hope my question is clear.