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.

Setting Up

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.

Step One

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.

Modify the text of the Button control to “Show Hidden Field” as this is what will be shown on the button.

Step Two

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.

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.

Output

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.

hiddenfield 1

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.

Download Source Files