【问题标题】:Set Radiobuttonlist Selected from Codebehind设置从代码隐藏中选择的 Radiobuttonlist
【发布时间】:2011-08-05 10:46:24
【问题描述】:

嘿,我有一个单选按钮列表,并试图根据会话变量将其中一个单选按钮设置为选中,但事实证明这是不可能的。

<asp:radiobuttonlist id="radio1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
   <asp:listitem id="option1" runat="server" value="All"/>
   <asp:listitem id="option2" runat="server" value="1" />
   <asp:listitem id="option3" runat="server" value="2" />
</asp:radiobuttonlist> 

即如何在后面的代码中将 option2 设置为选中?

【问题讨论】:

  • listitem 没有 id 属性

标签: asp.net radiobuttonlist


【解决方案1】:

我们可以通过值来改变项目,这里是诀窍:

radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2

【讨论】:

    【解决方案2】:
    var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
    var radio = rad_id.getElementsByTagName("input");
    radio[0].checked = true;
    
    //this for javascript in asp.net try this in .aspx page
    

    //如果选择其他单选按钮,像这样将[0]增加到[1]或[2]

    【讨论】:

    • radio_btn_lst : 你的单选按钮列表 ID
    【解决方案3】:

    试试这个选项:

    radio1.Items.FindByValue("1").Selected = true;
    

    【讨论】:

    • 这个解决方案对我有用,而 Marquito 的由于某种原因没有。原因可能是因为我为第一项设置了
    【解决方案4】:

    在我看来,最好的选择是将Value 属性用于ListItem,该属性在RadioButtonList 中可用。

    我必须指出,ListItem 确实 具有 ID 属性。

    因此,在您的情况下,选择第二个元素(option2):

    // SelectedValue expects a string
    radio1.SelectedValue = "1"; 
    

    或者,您可以提供一个 int 给 SelectedIndex。

    // SelectedIndex expects an int, and are identified in the same order as they are added to the List starting with 0.
    radio1.SelectedIndex = 1; 
    

    【讨论】:

      【解决方案5】:

      你可以这样做:

      radio1.SelectedIndex = 1;
      

      但这是最简单的形式,随着 UI 的增长,很可能会出现问题。例如,如果团队成员在option2 上方的RadioButtonList插入 一个项目,但不知道我们在代码隐藏中使用幻数 来选择- 现在应用选择了错误的索引!

      Maybe you want to look into using FindControl in order to determine the ListItem actually required, by name, and selecting appropriately.例如:

      //omitting possible null reference checks...
      var wantedOption = radio1.FindControl("option2").Selected = true;
      

      【讨论】:

      • 我想知道如何在 ListItem 上执行 FindControl,因为它缺少 ID 属性。我能回忆起的唯一属性是 Selected、Enabled、Text 和 Value。有什么想法吗?
      • listitem 没有 id 属性,因此我会选择stackoverflow.com/a/11582680/1271898(Marquito 的回答)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 2018-08-23
      相关资源
      最近更新 更多