Tuesday, May 20, 2008

Adding Radio Button to GridView

First add a literal control as shown below and in GridView1_RowCreated event which will run for every row. assign the text value of literal control. and u can add as many attributes u want in radio button.make one thing very clear that u can use web control or html server control because they are server control and when your gridview rendered it generate there own unique id and name. when you want to change the value or their status like checked/unchecked use Literal lc = (Literal)e.Row.FindControl("Literal1"); and change the text of literal control based on your requirement. where e is GridViewRowEventArgs you will get it in any gridview specific event like click etc.

<asp:GridView ID="GridView1" runat="server">

<asp:TemplateField HeaderText="Radio"> <ItemTemplate>

<asp:Literal ID="Literal1" runat="server"></asp:Literal>

</ItemTemplate>

</asp:TemplateField>

</asp:GridView>

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

Literal lc = (Literal)e.Row.FindControl("Literal1");

lc.Text = lc.Text = String.Format("<input type='radio'

name='radiogroup' id=" + e.Row.RowIndex);

if (e.Row.RowIndex == 0)

lc.Text = lc.Text + " checked='checked'";

lc.Text = lc.Text + "/>";

}

}

No comments: