ASP.NET:如何通过字符串值设置RadioButtonList的选中项?
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;:SelectedItemis aListItemobject, 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 itsSelectedproperty to true, that’s far more verbose than usingSelectedValue.ResignationTypeRBList.SelectedIndex = _request.ResignationType;:SelectedIndexexpects an integer (the zero-based position of the item you want to select), but_request.ResignationTypeis 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, whereasSelectedValuerelies on the stableValueattribute.
内容的提问来源于stack exchange,提问作者gymcode

