The RadioButtonList Web Control

The RadioButtonList Web Control

The RadioButtonList control acts as a parent control for a collection of radio button list items. All child items of RadioButtonList are rendered by using a RadioButton control. A RadioButtonList control can have either no items or one item selected. The SelectedItem property returns the selected element as a ListItem object. However, you have no guarantee that only one item is selected at any given time. For this reason, be extremely careful when you access the SelectedItem property of a RadioButtonList control. Depending on the structure and flow of your code, the item returned could be a null object. A workaround that always shields you from unpleasant surprises is wrapping any call to Selected­Item in a try/catch block, but don’t abuse this technique because a try/catch block is always costly. An even better solution is to design your code to eliminate the risk of returning an unselected item.

The contents of a RadioButtonList control can be obtained from a data source, as shown here:

You also need to programmatically set the DataSource property as ­follows:

rbEmployees.DataSource = myDataTable;

The RadioButtonList control supports data binding by using five properties: DataSource, DataMember, DataTextField, DataValueField, and DataTextFormatString. These properties behave in the same way as the properties of controls discussed earlier in the chapter.

Programmers and designers who work with data bound controls in lists are always greatly concerned about content presentation. A list of items can flow horizontally or vertically, can be expressed in a fixed number of columns or rows, and so on.

Some Web controls, such as RadioButtonList, accept layout directives. For example, you can control how a list is rendered by using the RepeatLayout and/or RepeatDirection properties of RadioButtonList. RepeatLayout governs the default layout in which the list items are rendered within a table, ensuring the vertical alignment of the companion text. The alternative is displaying the items as free HTML text using blanks and breaks to guarantee a minimum of structure. With or without a tabular structure, RepeatDirection controls how the items flow. Feasible values for RepeatDirection are Vertical (the default) and Horizontal. The RepeatColumns property determines how many columns the list should have. The default value of 0 indicates that all items are displayed in a single row. The direction of that row—vertical or horizontal—depends on the value of RepeatDirection.