Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

asp.net - Set Radiobuttonlist Selected from 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> 

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The best option, in my opinion, is to use the Value property for the ListItem, which is available in the RadioButtonList.

I must remark that ListItem does NOT have an ID property.

So, in your case, to select the second element (option2) that would be:

// SelectedValue expects a string
radio1.SelectedValue = "1"; 

Alternatively, yet in very much the same vein you may supply an int to SelectedIndex.

// SelectedIndex expects an int, and are identified in the same order as they are added to the List starting with 0.
radio1.SelectedIndex = 1; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...