You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET:如何通过字符串值设置RadioButtonList的选中项?

Correct Way to Set Selected State for ASP.NET RadioButtonList from SharePoint Data

Let’s break this down clearly—here’s the correct approach and why the others don’t work:

The right method to set your RadioButtonList’s selected state using the value from your SharePoint list is:

ResignationTypeRBList.SelectedValue = _request.ResignationType;

Why this works:

The SelectedValue property of a RadioButtonList is purpose-built to match directly against the Value attribute of its ListItem elements. Looking at your control markup:

<asp:RadioButtonList ID="ResignationTypeRBList" RepeatDirection="Horizontal" runat="server" CausesValidation="false">
    <asp:ListItem Text="Resignation" Value="Resignation" Selected="True"></asp:ListItem>
    <asp:ListItem Text="NPL" Value="NPL"></asp:ListItem>
    <asp:ListItem Text="Others" Value="Others"></asp:ListItem>
</asp:RadioButtonList>

Each ListItem has a Value that matches its display text, and _request.ResignationType (pulled from SharePoint) should be a string matching one of these values. Assigning this string to SelectedValue automatically finds and selects the corresponding ListItem—this is the cleanest, most maintainable approach.

Why the other methods are incorrect:

  • ResignationTypeRBList.SelectedItem = _request.ResignationType;:
    SelectedItem is a ListItem object, not a string. You can’t directly assign a string to it—this will throw a compile-time error. While you could first find the matching ListItem (e.g., ResignationTypeRBList.Items.FindByValue(_request.ResignationType)) and set its Selected property to true, that’s far more verbose than using SelectedValue.

  • ResignationTypeRBList.SelectedIndex = _request.ResignationType;:
    SelectedIndex expects an integer (the zero-based position of the item you want to select), but _request.ResignationType is a string. This will also cause a compile error due to type mismatch. Even if you converted the string to an index, this approach is fragile—reordering ListItems in your markup would break the index, whereas SelectedValue relies on the stable Value attribute.

内容的提问来源于stack exchange,提问作者gymcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:29:17