Asp.net
設置從程式碼隱藏中選擇的 Radiobuttonlist
嘿,我有一個單選按鈕列表,並試圖根據會話變數將其中一個單選按鈕設置為選中,但事實證明這是不可能的。
<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>即如何在後面的程式碼中將 option2 設置為選中?
你可以這樣做:
radio1.SelectedIndex = 1;但這是最簡單的形式,隨著 UI 的增長,很可能會出現問題。例如,如果團隊成員在上面插入了一個項目,但不知道我們在程式碼隱藏中使用幻數來選擇 - 現在應用程序選擇了錯誤的索引!
RadioButtonList``option2也許您想研究使用FindControl以確定
ListItem實際需要的名稱,並進行適當的選擇。例如://omitting possible null reference checks... var wantedOption = radio1.FindControl("option2").Selected = true;
在我看來,最好的選擇
Value是ListItem使用RadioButtonList.我必須說
ListItem沒有ID屬性。因此,在您的情況下,選擇第二個元素(option2):
// SelectedValue expects a string radio1.SelectedValue = "1";或者,您可以為 SelectedIndex 提供一個 int。
// SelectedIndex expects an int, and are identified in the same order as they are added to the List starting with 0. radio1.SelectedIndex = 1;