How to Use the HiddenField Control in Visual Basic.NET
This tutorial will show you how to use the HiddenField control in Visual Basic.NET. This control enables a developer to store a non-displayed value in the rendered HTML of the page. It is used to store a value that needs to be persisted across multiple postbacks to the server. Think of it as a dynamic field that continues to be available regardless of how many times a button is clicked and information is posted back to the page.
If you have not done so, open Visual Studio and create an empty web site using the Visual Basic template. Name the web site HiddenFieldControl-VB. Again using the Visual Basic template, add a web form called Default.aspx to the web site.
You should be in the source view of Default.aspx, if not change the view to source at the bottom of the page window. In the open div tags, place a HiddenField control, Button control, and a Label control.
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Show Hidden Field" />
Clicked <asp:Label ID="Label1" runat="server"></asp:Label> times
Modify the text of the Button control to “Show Hidden Field” as this is what will be shown on the button.
Switch to design view and double click on the “Show Hidden Field” button. This will create a Button1_Click event handler in the code behind page. We will set the text of Label1 to the value of HiddenField1.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If (HiddenField1.Value = Nothing) Then
HiddenField1.Value = "0"
'Increment the HiddenField value by 1
HiddenField1.Value = Val(HiddenField1.Value) + 1
Label1.Text = HiddenField1.Value
We use an If statement to check if the value of HiddenField1 has anything in it and if not we give it a value of 0. We then convert the value of HiddenField from String to Integer with the Val function and increment it by one.
Run the page and click the “Show Hidden Field” button to run the Button1_Click event method. Keep clicking the button and you will see that the label keeps count of how many times the button has been clicked.
Normally view state, session state, and cookies are used to maintain the state of a Web Forms page. However, if these methods are disabled or are not available, you can use the HiddenField control to store state values.
Thanks for reading and make sure to download the source files to get a better understanding of how the code works.