Archive for data grid

It’s all gone radio rental

Posted in ASP / ASP.Net with tags , , , on July 19, 2008 by Si

Feel free to leave now if you’ve had enough of radio buttons….

So having dealt with radio buttons on my filter (read my other post, Missing / (in)action for background), I had the next challenge of getting radio buttons in a gridview. “Template Columns” I hear you shouting at me, and you’d be right. While there is a built-in column type for checkboxes, the same thing doesn’t exist for radio buttons. So a quick bit of markup like:

<asp:TemplateColumn><ItemTemplate><asp:RadioButton ..... /></ItemTemplate></asp:TemplateColumn>

you’d think would work nicely. But it doesn’t. Try it, and you’ll find that you can select the radio button in each data row, at the same time. The idea is, of course, that only one would be selected at a time. Something is going slightly wrong here.

Have a butcher’s at the air force (butcher’s hook = look, air force = source) and you’ll see that each rendered <input> element has a different name attribute. The browser uses this attribute to group radio buttons together, so as far as the browser is concerned each radio button is in its own group and so can be selected at the same time.

The two and six (=fix) for this is to use a Literal control in the item template,

<asp:Literal ID="RadioButtonMarkup" runat="server"><asp:Literal>

then override the gridview’s RowCreated event with something like:

Protected void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)

{

If (e.Row.RowType == DataControlRowType.DataRow}

{

' Grab a reference to the Literal control

Literal outputRow = (Literal)e.Row.FindControl("RadioButtonMarkup");

' Output the markup except for the "checked" attribute

outputRow.Text = String.Format( "<input type="radio" name="radioButtonGroup" " & _ "id="RowSelector{0}" value="{0}" />", e.Row.RowIndex);

}

}

Job done. You get a radio button in each row, and you can only select one at a time. This also has the advantage that you can modify the code should you need to (e.g. I am changing this so depending on a parameter this will display radio buttons or check boxes).

There is still the issue of remembering the selected item after postback. This can be done, I suggest reading the rest of the article from which I half-inched (=pinched) the above: Microsoft ASP.net – Adding a GridView Column of Radio Buttons. Essentially it involves adding a private property to store an ID of the selected item, then checking for that in the RowCreated handler above.

Si.

btw: radio rental = mental

Advertisements