Ste*_*ieB 17 asp.net radiobuttonlist
嘿,我有一个radiobuttonlist,并尝试根据会话变量设置其中一个radiobuttons,但证明是不可能的.
<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>
Run Code Online (Sandbox Code Playgroud)
即如何在后面的代码中将option2设置为选中?
mar*_*ito 20
最好的选择,在我看来,是使用Value的财产ListItem,这是可用的RadioButtonList.
我必须此话是ListItem它不具有一个ID属性.
因此,在您的情况下,要选择第二个元素(option2):
// SelectedValue expects a string
radio1.SelectedValue = "1";
Run Code Online (Sandbox Code Playgroud)
或者,您可以以非常相同的方式向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;
Run Code Online (Sandbox Code Playgroud)
Gra*_*mas 15
你可以这样做:
radio1.SelectedIndex = 1;
Run Code Online (Sandbox Code Playgroud)
但这是最简单的形式,并且随着UI的增长,很可能会出现问题.比如说,如果团队成员在上面插入一个项目,但不知道我们在代码隐藏中使用魔术数字来选择 - 现在应用程序选择了错误的索引!RadioButtonListoption2
也许您想要研究使用FindControl来确定ListItem实际需要的名称,并进行适当的选择.例如:
//omitting possible null reference checks...
var wantedOption = radio1.FindControl("option2").Selected = true;
Run Code Online (Sandbox Code Playgroud)
sha*_*zia 14
试试这个选项:
radio1.Items.FindByValue("1").Selected = true;
Run Code Online (Sandbox Code Playgroud)
我们可以按值更改项目,技巧如下:
radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104389 次 |
| 最近记录: |