-1

So I have a sipme ASP.NET Web Page that prints the info of one's gender stacked dynamically in a radio button list:

protected void Page_Load(object sender, EventArgs e)
{
    String[] genders = new String[2];
    genders[0] = "Male";
    genders[1] = "Female";
    RadioButtonList1.DataSource = genders;
    RadioButtonList1.DataBind();
    RadioButtonList1.Items.Add(new ListItem("Neutral", "Zero"));
}

protected void Button1_Click(object sender, EventArgs e)
{
    lblName.Text = txtName.Text;
    lblSurname.Text = txtSurname.Text;
    lblEmail.Text = txtMail.Text;
    Panel1.Visible = true;
    if (RadioButtonList1.SelectedIndex==0) lblGender.Text = "Male";
    else lblGender.Text = "Female";
}

However when I launch the site no matter what I select it always writes female it's like the RadioButtonList1.SelectedIndex==0 isn't working.

Any ideas?

David Mathers
  • 163
  • 2
  • 7
  • If nothing is happening (this does happen), cut the `Button1_Click` code out of the code-behind page and double-click the button on the design screen to recreate the click event in code-behind, then paste your code back in. – wazz Jun 11 '18 at 03:23

1 Answers1

1

Bind radiobuttonlist in page_Load with !IsPostBack condition or your radiobuttonlist will bind every time you post your page. So your radiobuttonlist is reset to index -1 when you click the button_click.

 protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            String[] genders = new String[2];
            genders[0] = "Male";
            genders[1] = "Female";
            RadioButtonList1.DataSource = genders;
            RadioButtonList1.DataBind();
            RadioButtonList1.Items.Add(new ListItem("Neutral", "Zero"));
        }
    }
Nagib Mahfuz
  • 833
  • 10
  • 19