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 |
|
4 |
No |
RadioButtonItemId |
|
4 |
No |
Field1 |
|
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. TheDataAdapter
is used to fill aDataTable
in a newDataSet
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. TheBindingManagerBase
is obtained for the TBL0709 table in theDataSet
, a handler is attached to manage thePositionChanged
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 boundTextBox ...
Get ADO.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.