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>
I.e How can I set option2 to selected in code behind ?
We can change the item by value, here is the trick:
// if you select other radiobutton increase [0] to [1] or [2] like this
You could do:
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
aboveoption2
but doesn't know we use magic numbers in code-behind to select - now the app selects the wrong index!Maybe you want to look into using FindControl in order to determine the
ListItem
actually required, by name, and selecting appropriately. For instance:Try this option:
The best option, in my opinion, is to use the
Value
property for theListItem
, which is available in theRadioButtonList
.I must remark that
ListItem
does NOT have an ID property.So, in your case, to select the second element (option2) that would be:
Alternatively, yet in very much the same vein you may supply an int to SelectedIndex.