I've a button and a textbox. I want a value to be entered in textbox and when I click on button the page will reload but the value should still be in the textbox. How can I do that. The following code doesn't work
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ViewState["value"] != null)
{
TextBox1.Text = ViewState["value"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["value"] = TextBox1.Text;
Response.Redirect("default.aspx");
}
}
}
Viewstate can retain the value only till when you are on the same page. You are redirecting to other page. So instead of using viewstate use session.
Response.Redirect does what it says - redirects the request to a NEW page. ViewState won't get applied, ever. If you need a redirection, consider using session instead.
If you don't need a redirection, simply don't redirect and update only parts of the page that need to be updated.
asp.net webform have already maintained the viewstate on page refresh . don't need any code for handle this operation .
See this : http://www.w3schools.com/aspnet/showaspx.asp?filename=demo_aspnetviewstate
referred from : http://www.w3schools.com/aspnet/aspnet_viewstate.asp
and see this discussion
try this
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ViewState["value"] != null)
{
TextBox1.Text = Session["value"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["value"] = TextBox1.Text;
Response.Redirect("default.aspx");
}
}
}
Since you are redirecting to a new VIEW so VIEWSTATE will not be of any HELP. SO,Use Session
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["value"] != null)
{
TextBox1.Text = Session["value"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["value"] = TextBox1.Text;
Response.Redirect("default.aspx");
}
}
}