How to get the value of a Hidden column in a GridView using C#



This article explains how to retrieve the value of a cell in a hidden column when a user selects a row in a GridView with a hidden column.

How to Hide a column in a GridView:

To hide a column we have to use a hidden field as follows:

E.g.: <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("ProductId") %>' />

Above I am using a Value attribute to retrieve a data from a 'ProductId column.

Here I am displaying 4 column values in a GridView. In a GridView I am using "select" link, when a user selects a row in a GridView that has a selected row and a cell value is to be retrieved.

How to create a "select" link column in a GridView :

A "Select" Link can be built using "CommandField" as follows:

<asp:CommandField ShowSelectButton="True" />

In .aspx page

<asp:GridView ID="Gridivew1" runat ="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" OnRowDataBound="Gridivew1_RowDataBound" OnSelectedIndexChanged="Gridivew1_SelectedIndexChanged" >
<Columns>
<
asp:CommandField ShowSelectButton="True" />

<asp:TemplateField HeaderText ="ProductName">
<ItemTemplate>
<
asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("ProductId") %>' />

<asp:Label ID ="lblProductName1" runat ="server" Text =''>
</asp:Label>

</ItemTemplate>
</
asp:TemplateField>
<
asp:TemplateField HeaderText ="ProductName">
<ItemTemplate>
<
asp:Label ID ="lblQuantityPerUnit" runat ="server" Text =''>
</asp:Label>
</
ItemTemplate>
</
asp:TemplateField>
<
asp:TemplateField HeaderText ="UnitPrice">
<ItemTemplate>
<
asp:Label ID ="lblUnitPrice" runat ="server" Text =''>
</asp:Label>
</
ItemTemplate>
</
asp:TemplateField>
</
Columns>
<
RowStyle BackColor="White" ForeColor="#330099" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
<
asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT * FROM [Products]"></asp:SqlDataSource>

Next Select your GridView events. Double click on SelectedIndexChanged Event and write the following code in the .aspx.cs page:

protected void Gridivew1_SelectedIndexChanged(object sender, EventArgs e)
{

string strValue=((HiddenField)Gridivew1.SelectedRow.Cells[1].FindControl("HiddenField1")).Value;

string strValue2 =((Label)Gridivew1.SelectedRow.Cells[1].FindControl("lblProductName1")).Text ;

Response.Write("Product Id=" + strValue + "product=" + strValue2);
}


Thanks for reading my article!

Up Next
    Ebook Download
    View all
    Learn
    View all