Tuesday, 31 December 2013

Is viewstate of the control is maintained when its visible property is false in C# ASP.NET

Yes, When we set visible ='false' for any control, the control is not rendered into the form but its state is maintained with the help of viewstate.
If we set EnableViewState = 'false' for any control it means its state will not be maintained. 

For Example :-

aspx page
<form id="myForm" runat="server">
    <div>
 
        <asp:TextBox ID="txtFirstValue" runat="server">     </asp:TextBox>
        <asp:Button ID="btnClick"
            runat="server" Text="Button" onclick="btnClick_Click />
 
        <asp:TextBox ID="txtSecondValue" runat="server" Visible="false">1</asp:TextBox>
 
    </div>
    </form>


aspx.cs page
public partial class Index : System.Web.UI.Page
{
    int number;
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btnClick_Click(object sender, EventArgs e)
    {
        txtFirstValue.Text = txtSecondValue.Text;
        number = Convert.ToInt32(txtSecondValue.Text);
        number++; //To increment by 1
        txtSecondValue.Text = number.ToString();
    }
}

Output of this program is : 1,2,3,4,5,6 etc. It means every time viewstate is maintained even visible property is false.
If we want that viewstate should not be maintained for a control we will do something like this

<asp:textbox id="txtSecondValue" runat="server" visible="false"  EnableViewState="false">1</asp:textbox>

Now every time output will be 1 because no viewstate was maintained.


That’s it!!…..Happy Programming...

No comments:

Post a Comment