UncleCoder.com

UncleCoder.com

Free programming examples and instructions

C# Data list to Viewstate

Demo and Code for how to assign data list into viewstate Asp.net c#

by Athil


Posted on 30 Mar 2017 Category: Asp.net Views: 1266

Edited on 10 Aug 2017


DEMO

Hi,  Here I am going to show how can we assign a C# list object to Viewstate and vice-versa. We can assign directly as Session in the case of view state. For that, we need to add a key work Serializable on above the line of data class model.

  [Serializable]
    public class User {
        public string Name { get; set; }
        public string Address { get; set; }
        public DateTime Datetime { get; set; }
    }

 

Full example

On Client Side

    <form id="form1" runat="server">
    <div>
    
        Enter&nbsp; your name and address and press Set data to view state button<br />
        And Enter the Retrieve From View State button
        <br />
        <br />
        Name: <asp:TextBox ID="TxtNameSet" runat="server"></asp:TextBox>
    
    </div>
        Address:
        <asp:TextBox ID="txtAddressSet" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
        <p>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Set Data to view state" />
        </p>
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Retrieve From View state" />
        <br />
        Name: <asp:TextBox ID="txtNameGet" runat="server"></asp:TextBox>
        <br />
        Address:
        <asp:TextBox ID="TxtAddressGet" runat="server"></asp:TextBox>
    </form>

On Server Side


 

 [Serializable]
        public class User
        {
            public string Name { get; set; }
            public string Address { get; set; }
            public DateTime Datetime { get; set; }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            User ur = new User();
            ur.Address = txtAddressSet.Text;
            ur.Name = TxtNameSet.Text;
            ur.Datetime = DateTime.Now;

            ViewState["UserDetails"] = ur;

            lblMessage.Text = "Data Addedd to view state!!";
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            User ur = new User();
            ur = ViewState["UserDetails"] as User;
            txtNameGet.Text = ur.Name;
            TxtAddressGet.Text = ur.Address;

        }

 



Leave a Comment:


Advertisement