Saturday 20 August 2011

asp.net ViewState example: how to use ViewState in asp.net


<%@ Page Language="C#" %>

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

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        int clickCounter = 1;
        if (ViewState["ClickCounter"] == null)
        {
            clickCounter = 1;
        }
        else
        {
            clickCounter = (int)ViewState["ClickCounter"] + 1;
        }

        ViewState["ClickCounter"] = clickCounter;
        Label1.Text = "Button clicked " + clickCounter + " times.";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net ViewState example: how to use ViewState in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">asp.net ViewState example</h2>
        <asp:Label
            ID="Label1"
            runat="server"
            ForeColor="DarkGreen"
            Font-Size="Large"
            >
        </asp:Label>
        <br /><br />
        <asp:Button
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            ForeColor="HotPink"
            Font-Bold="true"
            Text="Show Button Click Status"
            />
    </div>
    </form>
</body>
</html>