2011-04-14 36 views
13

嘿,我有一个radiobuttonlist,并试图设置一个基于会话变量选定的单选按钮,但证明是不可能的。从Codebehind中选择设置Radiobuttonlist

<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> 

I.e我怎样才能在后面的代码中选择option2?

+0

listitem没有id属性 – 2014-05-30 13:45:47

回答

13

你可以这样做:

radio1.SelectedIndex = 1; 

但是,这是最简单的形式,并为您的UI增长将最有可能成为问题。举例来说,如果团队成员option2以上插入RadioButtonList中的项目,但不知道我们在代码隐藏中使用幻数选择 - 现在应用程序选择错误的索引!

也许你想看看使用FindControl为了确定ListItem实际需要,通过名称,并适当选择。例如:

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

我不知道如何在ListItem上执行FindControl,因为它缺少ID属性。只有我能记得的属性是Selected,Enabled,Text和Value。有任何想法吗? – marquito 2012-07-20 15:38:43

+0

listitem没有id属性,因此我会选择http://stackoverflow.com/a/11582680/1271898(Marquito的回答) – 2014-05-30 13:46:35

17

最好的选择,在我看来,是使用Value属性为ListItem,这是在RadioButtonList可用。

我必须说,ListItem确实不是有一个ID属性。

所以,你的情况,来选择将是第二个元素(选项2):

// 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; 
+0

感谢您的编辑+ Ryan。我应该做到了。 =) – marquito 2014-04-15 19:09:31

13

尝试使用此选项:

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

这个解决方案适用于我,而Marquito's没有出于某种原因。原因可能是因为我为第一个项目设置了 2015-01-23 20:00:58

0
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]这样

+0

添加说明 – NSNoob 2016-01-28 13:02:52

+0

radio_btn_lst:您的radiobuttonlist ID – 2016-01-29 13:40:47

0

我们可以改变项目的价值,这里是诀窍:

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