微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

设置从代码隐藏中选择的单选按钮列表

如何解决设置从代码隐藏中选择的单选按钮列表

| 嘿,我有一个单选按钮列表,并尝试根据会话变量将单选按钮设置为选中状态,但事实证明这是不可能的。
<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为在后面的代码中选择?     

解决方法

您可以这样做:
radio1.SelectedIndex = 1;
但这是最简单的形式,并且随着UI的增加,很可能会出现问题。举例来说,假设某个团队成员在
option2
上方的
RadioButtonList
中插入了一个项目,但不知道我们会在代码后面使用幻数进行选择-现在应用选择了错误的索引! 也许您想研究使用FindControl来确定实际需要的“ 4”(按名称),并进行适当选择。例如:
//omitting possible null reference checks...
var wantedOption = radio1.FindControl(\"option2\").Selected = true;
    ,我认为,最好的选择是对
ListItem
使用
Value
属性,这在ѭ2available中可用。 我必须指出“ѭ4”没有ID属性。 因此,在您的情况下,要选择第二个元素(option2):
// SelectedValue expects a string
radio1.SelectedValue = \"1\"; 
另外,您可以按照相同的方式为SelectedIndex提供一个int。
// SelectedIndex expects an int,and are identified in the same order as they are added to the List starting with 0.
radio1.SelectedIndex = 1; 
    ,试试这个选项:
radio1.Items.FindByValue(\"1\").Selected = true;
    ,我们可以按值更改项目,这是窍门:
radio1.ClearSelection();
radio1.Items.FindByValue(\"1\").Selected = true;// 1 is the value of option2
    ,
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]     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。