Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch primary key in GridView but don't display it?

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.

like image 969
Rahman Avatar asked Nov 18 '13 10:11

Rahman


2 Answers

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;
}
like image 143
Chris L Avatar answered Nov 01 '22 08:11

Chris L


<asp:GridView ... DataKeyNames="PrimaryKey" />
like image 2
Dmytro Rudenko Avatar answered Nov 01 '22 08:11

Dmytro Rudenko