One of an approach to save data for user is the ViewState. The ViewState allows ASP.NET to
repopulate form fields on each postback to the server, making sure that a
form is not automatically cleared when the user hits the submit button.
All this happens automatically, unless you turn it off, but you can
actually use the ViewState for your own purposes as well. Please keep in
mind though, that while cookies and sessions can be accessed from all
your pages on your website, ViewState values are not carried between
pages. Here is a simple example of using the ViewState, the value entered will be save between postbacks
On the aspx file:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:Label ID="lbl1" runat="server"></asp:Label>
<asp:Button ID="btn1" runat="server" Text="ViewState" OnClick="btn1_click"/> <br />
</div>
</form>
On the code file:
protected void btn1_click(object sender, EventArgs e)
{
string oldText = (string)ViewState["currentText"];
string newText = oldText + " " + txt1.Text;
//First, we assign this new value to the label
lbl1.Text = newText;
//Secondly, we replace the old value of the view state so that the new value is read the next //time
ViewState["currentText"] = newText;
txt1.Text = "";
}
Hope this helps!
Monday, December 26, 2011
An example of ViewState in ASP.NET
4:15 AM
Unknown
No comments
0 comments:
Post a Comment