Forcing a checkbox bound to a DataSource to update when it has not been viewed yet.
- by Scott Chamberlain
Here is a test framework to show what I am doing:
create a new project
add a tabbed control
on tab 1 put a button
on tab 2 put a check box
paste this code for its code
(use default names for controls)
public partial class Form1 : Form
{
private List<bool> boolList = new List<bool>();
BindingSource bs = new BindingSource();
public Form1()
{
InitializeComponent();
boolList.Add(false);
bs.DataSource = boolList;
checkBox1.DataBindings.Add("Checked", bs, "");
this.button1.Click += new System.EventHandler(this.button1_Click);
this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
}
bool updating = false;
private void button1_Click(object sender, EventArgs e)
{
updating = true;
boolList[0] = true;
bs.ResetBindings(false);
Application.DoEvents();
updating = false;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (!updating)
MessageBox.Show("CheckChanged fired outside of updating");
}
}
The issue is if you run the program and look at tab 2 then press the button on tab 1 the program works as expected, however if you press the button on tab 1 then look at tab 2 the event for the checkbox will not fire untill you look at tab 2.
The reason for this is the controll on tab 2 is not in the "created" state, so its binding to change the checkbox from unchecked to checked does not happen until after the control has been "Created".
checkbox1.CreateControl() does not do anything because according to MSDN
CreateControl does not create a
control handle if the control's
Visible property is false. You can
either call the CreateHandle method or
access the Handle property to create
the control's handle regardless of the
control's visibility, but in this
case, no window handles are created
for the control's children.
I tried getting the value of Handle(there is no public CreateHandle() for CheckBox) but still the same result.
Any suggestions other than have the program quickly flash all of my tabs that have data-bound check boxes when it first loads?
EDIT-- per Jaxidian's suggestion I created a new class
public class newcheckbox : CheckBox
{
public new void CreateHandle()
{
base.CreateHandle();
}
}
I call CreateHandle() right after updating = true same results as before.