[英]ASP Read value from RadioButtonList inside of a GridView
I have a ASP.NET GridView which I fill with data, one button, and one RadioButtonList with 4 radio buttons.我有一个 ASP.NET GridView,其中填充了数据、一个按钮和一个带有 4 个单选按钮的 RadioButtonList。 How can I get which radio button is selected by pressing a button outside of the GridView (using c# codebehind)?
如何通过按下 GridView 外部的按钮(使用 c# 代码隐藏)来获取选择的单选按钮? The button inside the GridView shall be used for removing a row (RowCommand event I think...)
GridView 内的按钮应用于删除一行(我认为是 RowCommand 事件...)
Code from within the GridView: 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>
To know which RadioButton was selected follow these steps from your current code:要了解选择了哪个 RadioButton,请按照当前代码中的以下步骤操作:
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.所以现在您已经填充了
CommandName
和CommandArgument
属性CommandArgument
会将行的索引传递给您的RowCommand
事件。
Then your RowCommand
event looks like this:然后您的
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);
}
}
}
}
Note : I would recommend adding Value
to your RadioButtons
so that you check against values and not text.注意:我建议向您的
RadioButtons
添加Value
,以便您检查值而不是文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.