[SOLVED] Input string never equals the random string

Issue

It should return "success", but it always returns the answer of "fail".

protected void Button3_Click(object sender, EventArgs e)
{
  Random rnd = new Random();
  randomNumber = (rnd.Next(100000, 999999)).ToString();
  Label1.Text = randomNumber;
}

protected void Button2_Click(object sender, EventArgs e)
{
  if (TextBox1.Text != randomNumber)
  {
    Label1.Text = "fail";
  }
  else
  {
    Label1.Text = "success";
  }
}

Here is the HTML part.

<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="Button" OnClick="Button3_Click" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Solution

Your randomNumber is a class-level field. Its value will not be persisted between requests.

If you want to persist the value between requests, then you need to store it in the ViewState:

private string RandomValue
{
    get { return (string)ViewState["RandomValue"]; }
    set { ViewState["RandomValue"] = value; }
}

protected void Button3_Click(object sender, EventArgs e)
{
    Random rnd = new Random();
    RandomNumber = (rnd.Next(100000, 999999)).ToString();
    Label1.Text = RandomNumber;
}

protected void Button2_Click(object sender, EventArgs e)
{
    if (TextBox1.Text != RandomNumber)
    {
        Label1.Text = "fail";
    }
    else
    {
        Label1.Text = "success";
    }
}

ASP.NET Page Life Cycle Overview

Answered By – Richard Deeming

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *