gpt4 book ai didi

c# - ASP 从 GridView 内的 RadioButtonList 读取值

转载 作者:行者123 更新时间:2023-12-04 05:01:28 26 4
gpt4 key购买 nike

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

最佳答案

要了解选择了哪个 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以便您检查值而不是文本。

关于c# - ASP 从 GridView 内的 RadioButtonList 读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16109330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com