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
BindRadioButton
in theAdoDotNet35Cookbook
database. 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
BindRadioButton
used in this solution is shown in Table 8-15.Table 8-15. BindRadioButton table schema
Column name
Data type
Length
Allow nulls?
Id
int
4
No
RadioButtonItemId
int
4
No
Field1
nvarchar
50
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
Form1
design surface:BindingNavigator
namedbindingNavigator
Button
namedsaveToolStripButton
on theBindingNavigator
control with itsText
property =Save ...
Get ADO.NET 3.5 Cookbook, 2nd Edition 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.