Reputation: 191
I am trying to keep the variable value after the post back. I tried it both by session variable and also Viewstate but failed to keep the value of random number same. Every time after button press (after page refresh) I am getting a new random value but I want to keep the same value.
//in code behind
public static int RandNumber{ get; set; }
protected void Page_Load(object sender, EventArgs e)
{
//by using session
Session["rand"] = rnd.Next(0, 10);
RandNumber = Int32.Parse(Session["rand"].ToString());
//by view state
int rand = rnd.Next(0, 10);
ViewState["KEY"] = rand;
RandNumber = Int32.Parse(ViewState["KEY"].ToString());
}
for post back in the form:
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
And tried to access in the page as below:
<p>Random No: <%= RandNumber %></p>
Upvotes: 1
Views: 1572
Reputation: 8877
Only set a new random number if it's not a post back by checking IsPostBack
public int RandNumber{ get; set; }
protected void Page_Load(object sender, EventArgs e)
{
//by using session
if(!IsPostBack){
Session["rand"] = rnd.Next(0, 10);
}
RandNumber = Int32.Parse(Session["rand"].ToString());
}
Upvotes: 4