O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.9. Binding a Group of Radio Buttons in a Windows Form

Problem

You need to bind a field in a database to a radio button and update the database with the radio button selected.

Solution

Use a hidden TextBox to retrieve and update the field value that corresponds to the radio button group. You can use the Tag property of each RadioButton control to hold its corresponding data field value.

The schema of table TBL0709 used in this solution is shown in Table 7-9.

Table 7-9. TBL0709 schema

Column name

Data type

Length

Allow nulls?

Id

int

4

No

RadioButtonItemId

int

4

No

Field1

nvarchar

50

Yes

The sample code contains seven event handlers:

Form.Load

Sets up the sample by creating a DataAdapter with the logic to select all records from table TBL0709 in the sample database and to update changes made back to the database. The DataAdapter is used to fill a DataTable in a new DataSet with the schema and data from TBL0709.

The text boxes displaying the data for the fields in the record are bound to the three columns in the table: Id, RadioButtonItemId, and Field1. The RadioButtonItemId TextBox is hidden. The BindingManagerBase is obtained for the TBL0709 table in the DataSet, a handler is attached to manage the PositionChanged event, and that handler is called to position the display on the first record.

Update Button.Click

Iterates over the group of radio buttons to identify the one selected. The Tag property for the selected radio button is transferred to the hidden bound TextBox ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required