How to Get Read Hidden Field Value from GridView in Asp.Net C# VB.Net

In some cases developers need to collect more data instead of DatakeyNames. In that cases developers use hidden field to retain those important data in GridView Template Column. Here in this article i will show how one can use hidden field to store some more important data into GridView Template Column & how can read data from this hidden field. Here I will use GridView SelectedIndexChanged event to explain the example. Hope you can use this technique in other ways whenever required.

How to read hidden field data in GridView Csharp

To do the Example First Create a DataBase Table:

CREATE TABLE [dbo].[Students](
	[Roll] [bigint] NOT NULL,
	[Name] [varchar](max) NOT NULL,
	[Email] [varchar](max) NOT NULL,
	[Address] [varchar](max) NOT NULL,
	[AdDate] [datetime] NOT NULL

Now Insert some Data into the Table:

INSERT INTO Students VALUES(1001,'Abul Kalam Azad','','Donia, Dhaka',GETDATE()-12)
INSERT INTO Students VALUES(1002,'Md. Afsarul Alam','','Mirpur, Dhaka',GETDATE()-12)
INSERT INTO Students VALUES(1003,'Md. Jahangir Alam','','Shonir Akhra, Dhaka',GETDATE()-25)
INSERT INTO Students VALUES(1004,'Akhtarul Islam','','Savar, Dhaka',GETDATE()-33)
INSERT INTO Students VALUES(1005,'A.K.M. Parvez','','Uttara, Dhaka',GETDATE()-5)

Now Modify the web.config file to connect to your Database like below:

    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now prepare the HTML Markup like below:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
             <asp:CommandField ShowSelectButton="True" />
             <asp:BoundField DataField="Roll" HeaderText="Roll" />
             <asp:TemplateField HeaderText="Name">
             <asp:HiddenField runat="server" ID="HiddenField1" Value='<%#Eval("Email")%>'></asp:HiddenField>
             <asp:Label runat="server" ID="Label2" Text ='<%#Eval("Name")%>'></asp:Label>

             <asp:BoundField DataField="Address" HeaderText="Address" />
             <asp:BoundField DataField="AdDate" HeaderText="Admission Date" />

            <SelectedRowStyle BackColor="Blue" ForeColor="White" />
        <br />
        <asp:Label ID="lbl" runat="server" Font-Bold="true"></asp:Label>

Note: I have added Select Button. I will use the Select Button SelectedIndexChanged Event later to get/read the HiddenField values.

Now bind data into the GridView:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
                SqlDataAdapter ad = new SqlDataAdapter("SELECT * from Students", conn);

            GridView1.DataSource = dt;

Note: Don’t forget to add “System.Data”,”System.Data.SqlClient”,”System.Configuration” namespaces

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim dt As DataTable = New DataTable()
            Using conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString)
                Dim ad As SqlDataAdapter = New SqlDataAdapter("SELECT * from Students", conn)
            End Using

            GridView1.DataSource = dt
        End If
    End Sub

Note: Don’t forget to add “System.Data”,”System.Data.SqlClient”,”System.Configuration” namespaces

Now time to handle GridView SelectedIndexChanged Event:
Add SelectedIndexChanged Event like below:
C# Code:

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        lbl.Text = "Email Address=" + ((HiddenField)GridView1.SelectedRow.Cells[1].FindControl("HiddenField1")).Value;

VB.Net Code:

    Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.SelectedIndexChanged
        lbl.Text = "Email Address=" + CType(GridView1.SelectedRow.Cells(1).FindControl("HiddenField1"), HiddenField).Value
    End Sub

Now run the project. Hope you will get your desired output. You can hide more information within GridView HiddenField rather than DataKeyNames & later you can use those HiddenFields values for different purposes without making another server trip.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net,, C#, Gridview, VB.Net
3 comments on “How to Get Read Hidden Field Value from GridView in Asp.Net C# VB.Net
  1. Temi says:

    Hi, Is there a way that i can add a checkbox at the top of the table that whn i check it, the table will be visible and when i uncheck it, it will be visible using C#.

  2. Milos says:

    Thank You for this tutorial. It helped a lot.

Leave a Reply

Your email address will not be published. Required fields are marked *