A RadioButtonList in a GridView

A GridView is to include a RadioButtonList in its presentation. The options are to be populated as fixed options, not taken from a database.

The example below takes values from the DotNetNuke Lists and displays them as a radio button list.

In the presentation file there is a GridView, called gdvMembership

<asp:GridView ID="gdvMembership" runat="server"
  AllowPaging="false"
  AllowSorting="false"
  AutoGenerateColumns="false"
  GridLines="none"
  cellspacing="1"
  border="0"
>
  <Columns>
    <asp:TemplateField ItemStyle-HorizontalAlign="left" ItemStyle-Width="80%">
    <ItemTemplate>
    <asp:RadioButton ID="rbnOptions" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Text")  %>' GroupName='<%# DataBinder.Eval(Container, "DataItem.Value")  %>' Checked='<%# DataBinder.Eval(Container, "DataItem.Selected")  %>' AutoPostBack="true" OnCheckedChanged="setSelection" />
    </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

In the code behind, a subroutine is used to populate the GridView and to set the selected item.

Private Sub Registration(ByVal SeclectedValue as string)
  Dim dt as DataTable = new DataTable
  dt.Columns.Add(New DataColumn("Text"))
  dt.Columns.Add(New DataColumn("Value"))
  dt.Columns.Add(New DataColumn("Enabled"))
  Dim row as dataRowrow = dt.newRow()
  row("Text") = "I am registered with the organisation"
  row("Value") = "Registered"
  row("Enabled") = True"
  If SelectedValue Is Nothing Then
    row("Selected") = False
  ElseIf SelectedValue = "Registered" Then
    row("Selected") = True
  Else
    row("Selected") = False
  End If
  dt.Rows.Add(row)row = dt.newRow()
  gdvMembership.DataSource = dt
  gdvMembership.DataBind()
End Sub

Whilst populating the rest of the page content the above sub-routine is called with the value of the registration status.

Registration(objIApplication.Membership)

Radio buttons of a different row in a GridView cannot be grouped together. The issue is caused by each row in the GridView being given a different ident.

The radiobuttons are therefore not of the same name once the page is rendered.

<input id=”dnn_ctr485_application_gdvMembership_rbnOptions_0″ name=”dnn_ctr485_application_gdvMembership_rbnOptions_1″…>

Use the GroupName parameter.

I had considered using JQuery to change uncheck the other options when the selection is changed. However, I chose to use an auto postback and a call to a function: don’t forget to add AutoPostBack=”true”.

Protected Sub setSelection(ByVal sender As Object, ByVal e As System.EventArgs)
  For Each row As GridViewRow In gdvMembership.Rows
    Dim rb As RadioButton = TryCast(row.FindControl("rbnCUOptions"), RadioButton)
    Dim rbn As RadioButton = TryCast(sender, RadioButton)
    If Not rb Is rbn Then
      rb.Checked = False
    End If
  Next
End Sub