2013-05-28 261 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; 
     } 
    } 
} 
相关问题