设置单选按钮列表从codebehind选择 [英] Set Radiobuttonlist Selected from Codebehind

查看:110
本文介绍了设置单选按钮列表从codebehind选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hey I have a radiobuttonlist and trying to set one of the radiobuttons to selected based on a session variable but proving impossible.

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

即如何设置选项2在code选择背后?

I.e How can I set option2 to selected in code behind ?

推荐答案

您可以这样做:

radio1.SelectedIndex = 1;

但是,这是最简单的形式和您的UI增长将最有可能成为问题。说,举例来说,如果一个团队成员的插入的在项目单选按钮列表上方选项2 但是不知道我们使用的幻数的在code-后面选择 - 现在的应用程序选择了错误的指数

But this is the most simple form and would most likely become problematic as your UI grows. Say, for instance, if a team member inserts an item in the RadioButtonList above option2 but doesn't know we use magic numbers in code-behind to select - now the app selects the wrong index!

也许你想看看使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol.aspx\">FindControl为了确定列表项实际需要,通过名称,以及适当地选择。例如:

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

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

这篇关于设置单选按钮列表从codebehind选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆