Search code examples
c#winformsdata-bindingcheckboxgroupbox

How to bind a custom control check box


I have been having issues with a custom check box control for a while now and had posted this Question... It appears that the problem isn't related to the events.

The custom control is a group box with a check box. When the check box is false, all the group controls should be disabled. It sounds simple but the problem is that when an internal control loses focus, the checked change event is fired.

After a bit more digging I think I have narrowed it down to the binding of the checked property to another object. When the binding is included it works incorrectly but with the binding removed everything works as expected.

I'm not sure how to resolve the issue now that it's been located.

Can anyone help?

Here is some code from my test application--

The Form: enter image description here

The form code:

public partial class Form1 : Form
{
    TestProperties m_TP;

    public Form1()
    {
        // Create instance of TestProperties
        m_TP = new TestProperties();

        InitializeComponent();

        BindControls();
    }

    private void BindControls()
    {
        // Bind the values to from the controls in the group to the properties class

        // When the line below is commented out the control behaves normally
        //this.checkedGroupBox1.DataBindings.Add("Checked", m_TP, "GroupChecked");
        this.numericUpDown1.DataBindings.Add("Value", m_TP, "SomeNumber");
        this.textBox1.DataBindings.Add("Text", m_TP, "SomeText");
        this.checkBox1.DataBindings.Add("Checked", m_TP, "BoxChecked");

        // Bind the values of the properties to the lables
        this.label4.DataBindings.Add("Text", m_TP, "GroupChecked");
        this.label5.DataBindings.Add("Text", m_TP, "SomeNumber");
        this.label6.DataBindings.Add("Text", m_TP, "SomeText");
        this.label8.DataBindings.Add("Text", m_TP, "BoxChecked");
    }
}

A property storage class:

class TestProperties
{
    public bool GroupChecked { get; set; }
    public decimal SomeNumber { get; set; }
    public string SomeText { get; set; }
    public bool BoxChecked { get; set; }

    public TestProperties()
    {
        GroupChecked = false;
        SomeNumber = 0;
        SomeText = string.Empty;
        BoxChecked = true;
    }
}

EDIT: Here is the source for my custom control:

/// <summary>
/// Custom control to create a checked group box.
/// Enables / disables all controls within the group depending upon the state of the check box
/// </summary>
public class CheckedGroupBox : System.Windows.Forms.GroupBox
{
    #region Private Member Variables
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Checkbox to enable / disable the controls within the group
    /// </summary>
    private CheckBox chkBox;

    /// <summary>
    /// Label for the group box which is set to autosize
    /// </summary>
    private Label lblDisplay;
    #endregion

    /// <summary>
    ///  Default constructor for the control
    /// </summary>
    public CheckedGroupBox()
    {
        // This call is required by the Windows Form Designer.
        InitializeComponent();

        // The text of these controls should always be empty.
        this.Text = "";
        this.chkBox.Text = "";
    }

    #region Events & Delegates

    /// <summary>
    /// Event to forward the change in checked flag
    /// </summary>
    public event EventHandler CheckedChanged;

    /// <summary>
    /// Event to forward the change in checked state of the checkbox
    /// </summary>
    public event EventHandler CheckStateChanged;

    private void chkBox_CheckedChanged(object sender, EventArgs e)
    {
        // Disable the controls within the group
        foreach (Control ctrl in this.Controls)
        {
            if (ctrl.Name != "chkBox" && ctrl.Name != "lblDisplay")
            {
                ctrl.Enabled = this.chkBox.Checked;
            }
        }

        // Now forward the Event from the checkbox
        if (this.CheckedChanged != null)
        {
            this.CheckedChanged(sender, e);
        }
    }

    private void chkBox_CheckStateChanged(object sender, EventArgs e)
    {
        // Forward the Event from the checkbox
        if (this.CheckStateChanged != null)
        {
            this.CheckStateChanged(sender, e);
        }
    }

    #endregion

    #region Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.chkBox = new System.Windows.Forms.CheckBox();
        this.lblDisplay = new System.Windows.Forms.Label();
        this.SuspendLayout();
        // 
        // chkBox
        // 
        this.chkBox.Location = new System.Drawing.Point(8, 0);
        this.chkBox.Name = "chkBox";
        this.chkBox.Size = new System.Drawing.Size(16, 16);
        this.chkBox.TabIndex = 0;
        this.chkBox.CheckStateChanged += new System.EventHandler(this.chkBox_CheckStateChanged);
        this.chkBox.CheckedChanged += new System.EventHandler(this.chkBox_CheckedChanged);
        // 
        // lblDisplay
        // 
        this.lblDisplay.AutoSize = true;
        this.lblDisplay.Location = new System.Drawing.Point(24, 0);
        this.lblDisplay.Name = "lblDisplay";
        this.lblDisplay.Size = new System.Drawing.Size(97, 13);
        this.lblDisplay.TabIndex = 1;
        this.lblDisplay.Text = "CheckedGroupBox";
        // 
        // CheckedGroupBox
        // 
        this.BackColor = System.Drawing.Color.AliceBlue;
        this.Controls.Add(this.chkBox);
        this.Controls.Add(this.lblDisplay);
        this.Size = new System.Drawing.Size(100, 100);
        this.ResumeLayout(false);
        this.PerformLayout();

    }
    #endregion

    #region Public properties

    [Bindable(true), Category("Appearance"), DefaultValue("Check Group Text")]
    public override string Text
    {
        get{ return this.lblDisplay.Text; }
        set{ this.lblDisplay.Text = value; }
    }

    [Bindable(true), Category("Appearance"), DefaultValue("Checked")]
    public System.Windows.Forms.CheckState CheckState
    {
        get{ return this.chkBox.CheckState; }
        set
        { 
            this.chkBox.CheckState = value; 

            foreach( Control ctrl in this.Controls )
            {
                if( ctrl.Name != "chkBox" && ctrl.Name != "lblDisplay" )
                {
                    ctrl.Enabled = this.chkBox.Checked;
                }
            }
        }
    }

    [Bindable(true), Category("Appearance"), DefaultValue("True")]
    public bool Checked
    {
        get{ return this.chkBox.Checked; }
        set
        { 
            this.chkBox.Checked = value; 

            foreach( Control ctrl in this.Controls )
            {
                if( ctrl.Name != "chkBox" && ctrl.Name != "lblDisplay" )
                {
                    ctrl.Enabled = this.chkBox.Checked;
                }
            }
        }
    }

    [Bindable(true), Category("Behavior"), DefaultValue("False")]
    public bool ThreeState
    {
        get{ return this.chkBox.ThreeState; }
        set{ this.chkBox.ThreeState = value; }
    }

    #endregion

}

Solution

  • You need to change the BindControls method as follows. The reason for this is that by default the controls are being updated to reflect the properties of m_TP, but when their values are changed the changes aren't being reflected in m_TP (I guess that the Leave events cause a rebinding of the controls to their datasources). By adding the DataSourceUpdateMode parameter the changes will be made bidirectionally.

    private void BindControls()
    {
        // Bind the values to from the controls in the group to the properties class
    
        // When the line below is commented out the control behaves normally
        this.checkedGroupBox1.DataBindings.Add("Checked", m_TP, "GroupChecked", false, DataSourceUpdateMode.OnPropertyChanged);
        this.numericUpDown1.DataBindings.Add("Value", m_TP, "SomeNumber", false, DataSourceUpdateMode.OnPropertyChanged);
        this.textBox1.DataBindings.Add("Text", m_TP, "SomeText", false, DataSourceUpdateMode.OnPropertyChanged);
        this.checkBox1.DataBindings.Add("Checked", m_TP, "BoxChecked", false, DataSourceUpdateMode.OnPropertyChanged);
    
        // Bind the values of the properties to the lables
        this.label4.DataBindings.Add("Text", m_TP, "GroupChecked");
        this.label5.DataBindings.Add("Text", m_TP, "SomeNumber");
        this.label6.DataBindings.Add("Text", m_TP, "SomeText");
        this.label8.DataBindings.Add("Text", m_TP, "BoxChecked");
    }