2011-04-14 53 views
13

嘿,我有一個radiobuttonlist,並試圖設置一個基於會話變量選定的單選按鈕,但證明是不可能的。從Codebehind中選擇設置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> 

I.e我怎樣才能在後面的代碼中選擇option2?

+0

listitem沒有id屬性 – 2014-05-30 13:45:47

回答

13

你可以這樣做:

radio1.SelectedIndex = 1; 

但是,這是最簡單的形式,併爲您的UI增長將最有可能成爲問題。舉例來說,如果團隊成員option2以上插入RadioButtonList中的項目,但不知道我們在代碼隱藏中使用幻數選擇 - 現在應用程序選擇錯誤的索引!

也許你想看看使用FindControl爲了確定ListItem實際需要,通過名稱,並適當選擇。例如:

//omitting possible null reference checks... 
var wantedOption = radio1.FindControl("option2").Selected = true; 
+0

我不知道如何在ListItem上執行FindControl,因爲它缺少ID屬性。只有我能記得的屬性是Selected,Enabled,Text和Value。有任何想法嗎? – marquito 2012-07-20 15:38:43

+0

listitem沒有id屬性,因此我會選擇http://stackoverflow.com/a/11582680/1271898(Marquito的回答) – 2014-05-30 13:46:35

17

最好的選擇,在我看來,是使用Value屬性爲ListItem,這是在RadioButtonList可用。

我必須說,ListItem確實不是有一個ID屬性。

所以,你的情況,來選擇將是第二個元素(選項2):

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

或者,但在很多同樣你可能會提供一個int來的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; 
+0

感謝您的編輯+ Ryan。我應該做到了。 =) – marquito 2014-04-15 19:09:31

13

嘗試使用此選項:

radio1.Items.FindByValue("1").Selected = true; 
+0

這個解決方案適用於我,而Marquito's沒有出於某種原因。原因可能是因爲我爲第一個項目設置了 2015-01-23 20:00:58

0
var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>'); 
var radio = rad_id.getElementsByTagName("input"); 
radio[0].checked = true; 

//this for javascript in asp.net try this in .aspx page 

//如果選擇其他單選按鈕增加[0] [1]或[2]這樣

+0

添加說明 – NSNoob 2016-01-28 13:02:52

+0

radio_btn_lst:您的radiobuttonlist ID – 2016-01-29 13:40:47

0

我們可以改變項目的價值,這裏是訣竅:

radio1.ClearSelection(); 
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2