View state Object in ASP.NET using VB.NET

This article shows the view state object in ASP.NET.
  • 2449

In this article we will learn about the view state in ASP.NET.

View State Object

Special object to manage information for current web page between different calls of same web page.

A hidden variable called _VIEWSTATE is used to hold the values of ViewState object and resubmit on every click.

ViewState is enabled by default so if you view a web form page in your browser you will see a line similar to the following near the form definition in your rendered HTML:

 <input type="hidden" name="__VIEWSTATE"
 value="dDwxNDg5OTk5MzM7Oz7DblWpxMjE3ATl4Jx621QnCmJ2VQ==" /> 
For example:
Create a web form having a login and password field and a login button. 
If login and password goes wrong for three times then disable the login button and give the message "Your Account is Blocked"
The form looks like this:

Figure 1.
Now double click on the login button of the design form and add the following code.
VB code:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

        If Not (TextBox1.Text = "abc" AndAlso TextBox2.Text = "xyz") Then

            If ViewState("ec") IsNot Nothing Then

                count = Convert.ToInt32(ViewState("ec"))

            End If


            count += 1


            ViewState("ec") = count


            Label1.Text = "count is " & count

            If count = 3 Then

                Button1.Enabled = False


                Label1.Text = "Your Account is blocked"

            End If

        End If

    End Sub


C# code:


protected void cmdLogin_Click(object sender, EventArgs e)


            if(! (txtLogin.Text == "abc" && txtPassword.Text == "xyz"))


                if (ViewState["ec"] != null)

                    count = Convert.ToInt32(ViewState["ec"]);




                ViewState["ec"] = count;


                lblMessage.Text = "count is " + count;

                if (count == 3)


                    cmdLogin.Enabled = false;

                    lblMessage.Text = "Your Account is blocked";






Now save and run the application and we entered wrong username and password.



Figure 2.


Now click on the button first time.



Figure 3.


Now click on the button second time.



Figure 4.


Now click on the button third time.


Figure 5.


More Articles

© 2020 DotNetHeaven. All rights reserved.