8.19. Binding a Group of Radio Buttons to a Windows Forms Data Field
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. Use the Tag property of each RadioButton control to hold its corresponding data field value.
Follow these steps:
The solution uses a table named
BindRadioButtonin theAdoDotNet35Cookbookdatabase. Execute the following T-SQL statement to create the table:USE AdoDotNet35Cookbook GO CREATE TABLE BindRadioButton( Id int NOT NULL PRIMARY KEY, RadioButtonItemId int NOT NULL, Field1 nvarchar(50) NULL )
The schema of table
BindRadioButtonused in this solution is shown in Table 8-15.Table 8-15. BindRadioButton table schema
Column name
Data type
Length
Allow nulls?
Idint4
No
RadioButtonItemIdint4
No
Field1nvarchar50
Yes
Execute the following T-SQL batch to create the sample data required by the solution:
USE AdoDotNet35Cookbook GO INSERT INTO BindRadioButton VALUES (1, 10, 'Field1.1') INSERT INTO BindRadioButton VALUES (2, 20, 'Field1.2') INSERT INTO BindRadioButton VALUES (3, 30, 'Field1.3') INSERT INTO BindRadioButton VALUES (4, 40, 'Field1.4')
Create a C# Windows Forms application named
DataBindWindowsFormRadioButton.Add the following controls to the
Form1design surface:BindingNavigatornamedbindingNavigatorButtonnamedsaveToolStripButtonon theBindingNavigatorcontrol with itsTextproperty =Save ...
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