Passing values using view States across PostBack in ASP.NET using VB.NET

In this article you will learn about the ViewState mechanism used for carrying values between PostBacks.
  • 5134


ViewState is the Mechanism that allows State values to be preserved across page PostBacks. Page level state information maintained, when an element on the Web form page causes a subsequent request to the server for the same page-referred to as postback. This is appropriately called View State as the data involved is usually, Though not necessarily. Shown to the user directly within page output.
When the page is processed the current state of the page and controls is hashed into a string and saved in the page as a Hidden Field, when the page is posted back to the server. The page parses the viewstate string at page initialization and restores property information in the page. ViewState is enabled by default. ViewState is an another approach for saving data for the user. While Cookies and Session can be accessed from all your pages from your website. ViewState values are not carried between pages. Here is a simple example of using the Viewstate to carry values between PostBacks.

Getting Started

  • Simply create a new ASP.NET web application. 
  • Drag one Textbox, two Button and a Label control on your page. The page will look like below.

  • You can also add controls manually by the below code.

    <%@ Page Title="Home Page" Language="vb"  AutoEventWireup="true"
        CodeBehind="Default.aspx.vb" Inherits="ViewStateObjectList._Default" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
    <html xmlns="" >
    <head id="Head1" runat="server">
        <form id="form1" runat="server">
            <asp:TextBox runat="server" id="NameField" />
            <br />
            <br />
            <asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" />
            <asp:Button runat="server" id="RefreshPage" text="Just submit" />
            <br /><br />
            Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" />
  • Then attach the below code in your code behind file.

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If ViewState("NameOfUser") IsNot Nothing Then
                NameLabel.Text = ViewState("NameOfUser").ToString()
                NameLabel.Text = "Not set yet..."
            End If
        End Sub
        Protected Sub SubmitForm_Click(ByVal sender As Object, ByVal e As EventArgs)
            ViewState("NameOfUser") = NameField.Text
            NameLabel.Text = NameField.Text
        End Sub

  • Now run your application.







In this article you learned what is ViewState mechanism to carry values between postbacks.


More Articles

© 2020 DotNetHeaven. All rights reserved.