Valerie Meunier

Valerie Meunier

  • 1.7k
  • 472
  • 21.3k

question about autopostback and viewstate

Jun 28 2022 6:51 PM


This code gives (with selected value 'c') : ok c

My question is: why is the value of variable id lost after postback and why is the SelectedValue not lost after postback, despite the fact that ViewState is enabled? What is the function in this case of ViewState?


aspx file:

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeBehind="WebForm1.aspx.cs" Inherits="mot.WebForm1" %>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
 <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>


using System;
namespace mot
    public partial class WebForm1 : System.Web.UI.Page
        internal string id="ok";
        protected void Button1_Click(object sender, EventArgs e)
            Label1.Text = id + " " + DropDownList1.SelectedValue;

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
            id = DropDownList1.SelectedValue;

Answers (2)