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 for update back to the database.
BindingManagerBase.PositionChanged
Selects the radio button corresponding to the data field. The code iterates over the group of radio buttons. When the Tag property of a radio button matches the value in the TextBox that is bound to the data field, the radio button is selected.
Move First Button.Click
Sets the current record of the bound controls to the first record by setting the Position property of the BindingManagerBase object to 0.
Move Previous Button.Click
Sets the current record of the bound controls to the previous record by decrementing the Position property of the BindingManagerBase object by 1.
Move Next Button.Click
Sets the current record of the bound controls to the next record by incrementing the Position property of the BindingManagerBase object by 1.
Move Last Button.Click
Sets the current record of the bound controls to the last record by setting the Position property of the BindingManagerBase object to the total number of records, as returned by the Count property, minus 1.
The C# code is shown in Example 7-17.
Example 7-17. File: RadioButtonForm.cs
// Namespaces, variables, and constants using System; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; private const String TABLENAME = "TBL0709"; private DataSet ds; private SqlDataAdapter da; private BindingManagerBase bm; // . . . private void RadioButtonForm_Load(object sender, System.EventArgs e) { // Create the DataSet. ds = new DataSet( ); // Create the select and update commands for the DataAdapter. String selectCommand = "SELECT Id, RadioButtonItemId, Field1 FROM " + TABLENAME; String updateCommand = "UPDATE " + TABLENAME + " " + "SET RadioButtonItemId=@RadioButtonItemId, Field1=@Field1 " + "WHERE Id=@Id"; // Create the DataAdapter. da = new SqlDataAdapter(selectCommand, ConfigurationSettings.AppSettings["Sql_ConnectString"]); da.UpdateCommand = new SqlCommand(updateCommand, da.SelectCommand.Connection); da.UpdateCommand.CommandType = CommandType.Text; da.UpdateCommand.Parameters.Add("@Id", SqlDbType.Int, 0, "Id"); da.UpdateCommand.Parameters.Add("@RadioButtonItemId", SqlDbType.Int, 0, "RadioButtonItemId"); da.UpdateCommand.Parameters.Add("@Field1", SqlDbType.NVarChar, 50, "Field1"); // Retrieve the data and schema for the table. da.FillSchema(ds, SchemaType.Source, TABLENAME); da.Fill(ds, TABLENAME); // Bind all of the controls, including hidden text box, to the DataSet. idTextBox.DataBindings.Add("Text", ds, TABLENAME + ".Id"); radioButtonItemIdTextBox.DataBindings.Add("Text", ds, TABLENAME + ".RadioButtonItemId"); radioButtonItemIdTextBox.Visible = false; field1TextBox.DataBindings.Add("Text", ds, TABLENAME + ".Field1"); // Get the binding manager base for the table. bm = BindingContext[ds, TABLENAME]; // Update the correct radio button in response to each record // reposition. bm.PositionChanged += new EventHandler(bm_PositionChanged); // Update the display for the first record. bm_PositionChanged(null, null); } private void updateButton_Click(object sender, System.EventArgs e) { // Retrieve the selected radio button based on the value in the // tag field to the hidden text box. foreach(RadioButton rb in radioButtonGroupBox.Controls) { if (rb.Checked) { radioButtonItemIdTextBox.Text = rb.Tag.ToString( ); break; } } // End the current update and update the record using the DataAdapter. bm.EndCurrentEdit( ); da.Update(ds.Tables[TABLENAME]); } private void bm_PositionChanged(Object sender, EventArgs e) { // Refresh the checked radio button when the current record changes. foreach(RadioButton rb in radioButtonGroupBox.Controls) { if (rb.Tag.ToString( ) == radioButtonItemIdTextBox.Text) { rb.Checked = true; break; } } } private void moveFirstButton_Click(object sender, System.EventArgs e) { bm.Position = 0; } private void movePreviousButton_Click(object sender, System.EventArgs e) { bm.Position -= 1; } private void moveNextButton_Click(object sender, System.EventArgs e) { bm.Position += 1; } private void moveLastButton_Click(object sender, System.EventArgs e) { bm.Position = bm.Count - 1; }
Discussion
While a RadioButton control can be set to simple-bind to data, there is no way to bind a group of RadioButton controls to a data source. Binding a single radio button to a data source isn't a particularly common requirementnor is it particularly usefulsince radio buttons are normally used in groups to allow an option to be selected from a group of mutually exclusive options.
Web Forms provides a RadioButtonList control that works as a parent control to a collection of radio button list items. It inherits from the ListControl class and as a result works similarly to the ListBox and DropDownList controls. There is no RadioButtonList control available for Windows Forms applications. For more information about the RadioButtonList class, see the MSDN Library.
Radio button data binding can be simulated in a Windows Form application by following these steps:
radioButtonItemIdTextBox.DataBindings.Add("Text", ds, TABLENAME + ".RadioButtonItemId");
bm = BindingContext[ds, TABLENAME];
The overload used in the sample takes two arguments, the data source and the data member, because the data source is a DataSet . For a DataTable , an overload of the BindingContext indexer is used that takes only the data source argument.
bm.PositionChanged += new EventHandler(bm_PositionChanged);
This event handler must be called for the first record, as done in the Form.Load event of the sample:
bm_PositionChanged(null, null);
Connecting to Data
Retrieving and Managing Data
Searching and Analyzing Data
Adding and Modifying Data
Copying and Transferring Data
Maintaining Database Integrity
Binding Data to .NET User Interfaces
Working with XML
Optimizing .NET Data Access
Enumerating and Maintaining Database Objects
Appendix A. Converting from C# to VB Syntax