2013-05-28 209 views
3

這可能是一個愚蠢的問題,但是如何根據現有數據預選一個RadioButtonList值?如何在GridView中的RadioButtonList中預先選擇一個值

我有這樣的代碼aspx文件裏面:

<asp:TemplateField ItemStyle-CssClass="ItemCommand" > 
    <HeaderTemplate></HeaderTemplate> 
    <ItemTemplate> 
     <asp:RadioButtonList runat="server" ID="rbLevel" RepeatLayout="Flow" RepeatDirection="Horizontal" > 
      <asp:ListItem Text="Read" Value="0"></asp:ListItem> 
      <asp:ListItem Text="Edit" Value="1"></asp:ListItem> 
     </asp:RadioButtonList> 
    </ItemTemplate> 
</asp:TemplateField> 

但我不能設置列表的價值。 RadioButtonList沒有SelectedValue屬性,設置DataValueField沒有效果,我不能一個接一個地設置值(使用類似於:Selected='<%# ((Rights)Container.DataItem).Level == 1 %>'),因爲數據綁定發生在列表中而不是特定項目。

+1

可以使用Gridview_RowDatabound事件前選擇基於價值在數據源上。 – MahaSwetha

回答

3

使用GridView的RowDataBound()方法來設置相應的單選按鈕列表:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
    {    
     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      RadioButtonList rbl = (RadioButtonList)e.Row.FindControl("rbLevel"); 
      // Query the DataSource & get the corresponding data.... 
      // ... 
      // if Read -> then Select 0 else if Edit then Select 1... 
      rbLevel.SelectedIndex = 0; 
     } 
    } 
2

ListItem選定的屬性嘗試如下

<asp:RadioButtonList runat="server" ID="rbLevel" RepeatLayout="Flow" RepeatDirection="Horizontal" > 
      <asp:ListItem Text="Read" Value="0" Selected ="True"></asp:ListItem> 
      <asp:ListItem Text="Edit" Value="1"></asp:ListItem> 
     </asp:RadioButtonList> 

OR

形式後面的代碼,你可以選擇的索引屬性

rbLevel.SelectedIndex = 0; 

如果所選項目依賴於數據源設置,數據綁定後,您可以找到該項目並將選擇設置爲下面的代碼。

rbLevel.Items.FindByValue(searchText).Selected = true; 
+0

我需要根據數據源中的數據預先選擇值(某些行將爲0,其中一些爲1)。 –

+0

是您需要選擇的第一件物品嗎? – Damith

+0

並不總是如我在問題中所說的那樣依賴於我從數據庫中獲得的數據。 –

3

U可以使用

rbLevel.SelectedIndex = 1;

OR

可以爲每個單選按鈕分配ID,然後使用

rbLevel.FindControl("option2").Selected = true;

希望這將工作:)

0

這是迄今爲止最好的答案我已經找到

protected void GridView1_DataBound(object sender, EventArgs e) 
{ 
    foreach (GridViewRow gvRow in GridView1.Rows) 
    { 
     RadioButtonList rbl = gvRow.FindControl("rblPromptType") as RadioButtonList; 
     HiddenField hf = gvRow.FindControl("hidPromptType") as HiddenField; 

     if (rbl != null && hf != null) 
     { 
      if (hf.Value != "") 
      { 
       //clear the default selection if there is one 
       rbl.ClearSelection(); 
      } 

      rbl.SelectedValue = hf.Value; 
     } 
    } 
} 
相關問題