【问题标题】:Radio button selected index not working单选按钮选择的索引不起作用
【发布时间】:2018-06-11 14:07:53
【问题描述】:

所以我有一个 sipme ASP.NET 网页,它打印一个单选按钮列表中动态堆叠的性别信息:

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";
}

但是,当我启动网站时,无论我选择什么,它总是写为女性,就像 RadioButtonList1.SelectedIndex==0 不起作用。

有什么想法吗?

【问题讨论】:

  • 如果什么都没有发生(这确实发生了),将Button1_Click代码从代码隐藏页面中剪掉,然后双击设计屏幕上的按钮以在代码隐藏中重新创建点击事件,然后将您的代码粘贴回去。

标签: asp.net radiobuttonlist selectedindex


【解决方案1】:

page_Load 中使用!IsPostBack 条件绑定radiobuttonlist,否则您的radiobuttonlist 将在您每次发布页面时绑定。因此,当您单击 button_click 时,您的 radiobuttonlist 将重置为索引 -1

 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"));
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 2017-02-08
    • 1970-01-01
    • 2017-11-25
    • 2018-02-13
    相关资源
    最近更新 更多