3

这可能是一个愚蠢的问题,但我如何才能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 %>':),因为数据绑定发生在列表而不是特定项目上。

4

4 回答 4

3

你可以使用

rbLevel.SelectedIndex = 1;

或者

可以为每个单选按钮分配 id 然后使用

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

希望这会奏效:)

于 2013-05-28T09:11:47.223 回答
3

使用 GridView 的RowDataBound()方法相应地设置 RadioButton 列表:

    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;
        }
    }
于 2013-05-28T10:08:26.450 回答
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>

或者

后面的表单代码可以通过选中的Index属性来设置

rbLevel.SelectedIndex = 0;

如果选中的item依赖于数据源,数据绑定后可以找到item并在后面的代码中设置选择如下。

rbLevel.Items.FindByValue(searchText).Selected = true; 
于 2013-05-28T09:05:02.033 回答
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;
        }
    }
}
于 2014-09-04T16:30:40.883 回答