Using a RadioButton to select a row in GridView
Some people need radiobutton for selection a row in gridview control and take a action after postback.
You should to use this code to resolve this issue.
<asp:GridView ID="_grid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder runat="server" ID="_holder" /></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>
This is code behind:
partial class SampleGridViewUI : Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this._grid.RowDataBound += new GridViewRowEventHandler( this.Grid_RowDataBound );
this._go.Click += new EventHandler( this.Go_Click );
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if ( ! this.IsPostBack )
{
this._grid.DataSource = this.Values;
this._grid.DataBind();
}
}
public IEnumerable<Group> Values
{
get
{
yield return new Group(1, "Administrators");
yield return new Group(2, "Users");
yield return new Group(3, "Power Users");
}
}
private void Grid_RowDataBound( Object sender, GridViewRowEventArgs e )
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Group group = (Group)e.Row.DataItem;
PlaceHolder holder = (PlaceHolder)e.Row.FindControl("_holder");
String innerhtml = String.Format("<input type='radio' name='sample' value='{0}'>", group.Id);
holder.Controls.Add(TemplateControl.ParseControl(innerhtml));
}
}
private void Go_Click(Object sender, EventArgs e)
{
String line = String.Format( "Id='{0}'", this.Request[ "sample" ] );
this.Response.Write(line);
}
public struct Group
{
private Int32 _id;
private String _name;
public Group(
Int32 id,
String name)
{
this._id = id;
this._name = name;
}
public Int32 Id { get { return this._id; } }
public String Name { get { return this._name; } }
}
} In Go_Click private function you should take a action with Group ID in Request[ "Sample" ] variable posted.