【问题标题】:ASP Read value from RadioButtonList inside of a GridViewASP 从 GridView 内的 RadioButtonList 读取值
【发布时间】:2020-12-11 02:07:08
【问题描述】:

我有一个 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>

【问题讨论】:

  • 我们可以从RowCommand event 获取一些代码sn-ps
  • 让我们也看看 GridView 的代码(标记和代码隐藏)
  • 您需要发布代码。
  • @HanletEscaño 后面的代码还没有写。我不知道如何从 RadioButtonList 中提取值:)
  • @Half_Baked 你发布的代码很好:)

标签: c# asp.net gridview


【解决方案1】:

要知道选择了哪个 RadioButton,请按照您当前代码中的以下步骤操作:

将您的按钮修改为:

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

所以现在您已经填写了 CommandNameCommandArgument 属性。CommandArgument 会将行的索引传递给您的 RowCommand 事件。

那么您的RowCommand 事件如下所示:

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);
            }
        }
    }
}

注意:我建议将Value 添加到您的RadioButtons,以便您检查值而不是文本。

【讨论】:

  • 哇!我将对此进行测试。我不确定我是否理解它是如何工作的...CommandArgument=""。我会调查的:)
  • @Half_Baked,它的工作方式是每次点击“删除”按钮时,按钮都会引发帖子,并触发 RowCommand 事件。使用 CommandArgument,您可以将任何值传递给 RowCommandEvent。有了这个值,我就知道选择了哪一行,并且可以很容易地找到 RadioButtonList。
  • 谢谢。很好解释。数据绑定怎么样?删除后我需要这样做吗?
  • 是的,您在从数据源中删除项目后重新绑定您的 GridView。
  • 谢谢!这是一个巨大的帮助! :)
猜你喜欢
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多