Please visit my new Web Site https://coderstechzone.com
In some cases developers need to collect more data instead of datakeynames. In that cases developers use hidden field to retain those important data. Here in this article i wil show how one can use hidden field to store some important data & how can read those. For simplicity here i use a product table & use ID in a hidden field to read them from server side SelectedIndexChanged event. The product table looks like below:
Now add a page in your project & also add a GridView like below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Hidden.aspx.cs" Inherits="GridView_Hidden" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>How to read GridView Hiden Field Data</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"> <HeaderStyle BackColor="Red" Font-Bold="True" ForeColor="White" /> <RowStyle BackColor="LightGray" /> <AlternatingRowStyle BackColor="LightGray" /> <Columns> <asp:CommandField ShowSelectButton="True" /> <asp:TemplateField HeaderText="Product Name"> <ItemTemplate> <asp:HiddenField runat="server" ID="HiddenField1" Value='<%#Eval("ID")%>'></asp:HiddenField> <asp:Label runat="server" ID="Label2" Text ='<%#Eval("Name")%>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Description" HeaderText="Description" /> <asp:BoundField DataField="Color" HeaderText="Color" /> <asp:BoundField DataField="Size" HeaderText="Size" /> </Columns> <SelectedRowStyle BackColor="Blue" ForeColor="White" /> </asp:GridView> </div> </form> </body> </html>Now under SelectedIndexChanged event write the below code to read hidden field value within gridview template column:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataTable dt = clsDBUtility.GetDataTable("SELECT * FROM PRODUCT"); GridView1.DataSource = dt; GridView1.DataBind(); Cache["Data"] = dt; } } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { string sValue = ((HiddenField)GridView1.SelectedRow.Cells[1].FindControl("HiddenField1")).Value; Response.Write("Product Id=" + sValue); }Now run the project & will get below like output:
Hope now you can read & use the hidden field vlaue from within a GridView.
1 comments:
I have a gridview in which I am setting certain rows to invisible. Now in javascript while computing the total of all values in last column in javascript, i want to access the invisible rows as well. How do I do that.
I WOULD BE DELIGHTED TO HEAR FROM YOU