ViewState with example in asp.net C#

Tuesday, December 21, 2010

ViewState with example in asp.net C#

  • ViewState:- The web is stateless but in asp.net, the state of page is maintained in the page itself automatically. How? The values are encryped and saved in hidden controls this is done automatically by the asp.net. This can be switched off/on manually for a single control.
Advantages :- Have a manually manage refreshing the page fields after submit.
Disadvantages:- Send additional data to the browser.
Example:-  We can store any thing in the viewstate manually and access it in same page.
      In this example we are saving the data table in view state and access it later in page.
Step1:- We  get the data table from database in page load event and store it in view state.

protected void Page_Load(object sender, EventArgs e)
    {
       string str = System.Configuration.ConfigurationManager.AppSettings["keyString"];
        SqlConnection con = new SqlConnection(str);
        SqlDataAdapter adap = new SqlDataAdapter("select * from product", con);
       DataTable dt = new DataTable();
       adap.Fill(dt);
       ViewState["TempTable"] = dt;
    }

Step2:-Now we access the table from viewstate on button click event and bind in gridview.

    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = (DataTable)ViewState["TempTable"];
        GridView1.DataBind();
    }

Complete Solution:-
Your Aspx page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    
    </form>
</body>
</html>

Now your aspx.cs page

using System.Web.UI;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = System.Configuration.ConfigurationManager.AppSettings["keyString"];
        SqlConnection con = new SqlConnection(str);
        SqlDataAdapter adap = new SqlDataAdapter("select * from product", con);
       DataTable dt = new DataTable();
       adap.Fill(dt);
       ViewState["TempTable"] = dt;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = (DataTable)ViewState["TempTable"];
        GridView1.DataBind();
    }
}

I hope it will help you.


No comments:

Post a Comment