问题
I have a ASP.NET GridView wich I fill with data, one button, and one RadioButtonList with 4 radio buttons. How can I get wich radio button is selected by pressing a button outside of the GridView (using c# codebehind)? The button inside the GridView shall be used for removing a row (RowCommand event I think...) Thanks!
Code from within the 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>
回答1:
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.
来源:https://stackoverflow.com/questions/16109330/asp-read-value-from-radiobuttonlist-inside-of-a-gridview