February 1008

Preselecting an option in RadioGroupLists

So in the spirit of a few recent bits of actual development work I’ve done recently I decided I needed a quick helper method to make pre-selecting RadioGroup items when binding a page with existing data. Setting the Text property for a TextBox is trivially simple (txtBoxName.Text = myValue), but getting the radio group item set to the correct value isn’t so simple and seems to need a loop through in order to get to the correct element to set.

private static void PreSelectRadioGroupOption(string valueToSelect, RadioButtonList radioGroup)
{
    foreach (ListItem item in radioGroup.Items) {
        if (item.Value == valueToSelect) {
            item.Selected = true;
            break; 
        }
    }
}

VB.NET

Private Shared Sub PreSelectRadioGroupOption(ByVal valueToSelect As String, ByVal radioGroup As RadioButtonList)
    For Each item As ListItem In radioGroup.Items
        If item.Value = valueToSelect Then
            item.Selected = True
            Exit For
        End If
    Next
End Sub

This lets you specify the radioGroup you want to set the selected item for and a string for the value to select. To use it simply call PreSelectRadioGroupOption("Pick Me", rgMyRadioGroup). It should be possible to make this method more generic and instead of only working for RadioButtonLists be able to specify DropDownLists or CheckboxLists etc. If anyone has such a method and wants to share it please feel free Open-mouthed

Add comment

(Will show your Gravatar icon)
  Country flag
biuquote
  • Comment
  • Preview
Loading