DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 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

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 requirement—nor is it particularly useful—since 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:

  1. Add the RadioButton controls to the form. For each radio button, set its Tag property to the data value that corresponds to the selection of the radio button.

  2. Create a hidden TextBox control to take the value of the selected RadioButton from the group.

  3. Bind the Text property of the TextBox to the data source:

    radioButtonItemIdTextBox.DataBindings.Add("Text", ds, TABLENAME +
        ".RadioButtonItemId");
  4. Get the BindingManagerBase for the DataTable using the indexer (Item property in VB.NET) of the BindingContext class.

    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.

  5. Attach an event handler for the PositionChanged event of the BindingManagerBase. This event indicates that the selected row in the DataTable has changed.

    bm.PositionChanged += new EventHandler(bm_PositionChanged);
  6. Create the event handler for the PositionChanged event. In the handler, iterate over the collection of radio buttons. Check the radio button that has a Tag matching the hidden TextBox that is bound to the data. This will select the radio button corresponding to the column value for the current row in the DataTable.

    This event handler must be called for the first record, as done in the Form.Load event of the sample:

    bm_PositionChanged(null, null);
  7. If the application permits modifying the data using the radio buttons, add code in the update method to iterate over the collection of radio buttons, transferring the Tag value of the checked radio button to the hidden data bound TextBox before the updating logic.

    [ Team LiB ] Previous Section Next Section