2

我有一个 ASP.NET GridView,我用数据、一个按钮和一个带有 4 个单选按钮的 RadioButtonList 填充。如何通过按下 GridView 外部的按钮(使用 c# 代码隐藏)来选择哪个单选按钮?GridView 内的按钮将用于删除一行(我认为是 RowCommand 事件......)

GridView 中的代码:

<Columns>
    <asp:BoundField DataField="name" HeaderText="Name" />
    <asp:BoundField DataField="value" HeaderText="Value" />
    <asp:TemplateField ShowHeader="false" HeaderText="Foo?">
        <ItemTemplate>
            <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal">
                <asp:ListItem Selected="true">Item 1</asp:ListItem>
                <asp:ListItem>Item 1</asp:ListItem>
                <asp:ListItem>Item 2</asp:ListItem>
                <asp:ListItem>Item 3</asp:ListItem>
                <asp:ListItem>Item 4</asp:ListItem>
            </asp:RadioButtonList>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField ShowHeader="false" HeaderText="">
        <ItemTemplate>
            <asp:Button ID="Button1" runat="server" Text="Remove" />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
4

1 回答 1

3

To know which RadioButton was selected follow these steps from your current code:

Modify your button to this:

<asp:TemplateField ShowHeader="false" HeaderText="">
    <ItemTemplate>
        <asp:Button ID="Button1" runat="server" Text="Remove" CommandArgument="<%#  ((GridViewRow) Container).RowIndex%>"
            CommandName="remove" />
    </ItemTemplate>
</asp:TemplateField>

so now you have CommandName and CommandArgument properties filled in. The CommandArgument will pass the index of the row to your RowCommand event.

Then your RowCommand event looks like this:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "remove")
    {
        int index = Convert.ToInt32(e.CommandArgument);
        if (index >= 0)
        { 
            //index is the row, now obtain the RadioButtonList1 in this row
            RadioButtonList rbl = (RadioButtonList)GridView1.Rows[index].FindControl("RadioButtonList1");
            if (rbl != null)
            {
                string selected = rbl.SelectedItem.Text;
                Response.Write("Row " + index + " was selected, radio button " + selected);
            }
        }
    }
}

Note: I would recommend adding Value to your RadioButtons so that you check against values and not text.

于 2013-04-19T16:51:03.447 回答