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.LoadSets up the sample by creating a
DataAdapterwith the logic to select all records from table TBL0709 in the sample database and to update changes made back to the database. TheDataAdapteris used to fill aDataTablein a newDataSetwith 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
RadioButtonItemIdTextBoxis hidden. TheBindingManagerBaseis obtained for the TBL0709 table in theDataSet, a handler is attached to manage thePositionChangedevent, 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
Tagproperty for the selected radio button is transferred to the hidden boundTextBox ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access