mathgenius mathgenius - 4 months ago 45
C# Question

Databinding doesn't work before Form Load - ComboBox Items initialized only after Form load

I have two ComboBoxes on a winform, one has all the values from a List "MyList" the other I want to have all the values from the selected index of the first, onwards. But I think there is a problem with when items are loaded into the ComboBoxes.

public partial class Form1 : Form
{
public Form1()
{
ComboBox box = new ComboBox();
box.DropDownStyle = ComboBoxStyle.DropDownList;
box.DataSource = MyList.ToList();
box.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
Tab_Page.Controls.Add(box);

ComboBox box2 = new ComboBox();
box2.DropDownStyle = ComboBoxStyle.DropDownList;
foreach (object o in box.Items)
{
box2.Items.Add(o);
}
Tab_Page.Controls.Add(box2);
box2.Items.RemoveAt(0);
//This last line throws an error
//"InvalidArgument=Value of '0' is not valid for 'index'."
}}


The error is because box2 has no items in its collection, even though box has all the values from the List at the moment this error is thrown.

So I was wondering how/when exactly are items loaded to the Items collection and how can I fix this?

Answer

Data-binding will not work before the form and control be in Created status and before the form and controls get visible they are not in Created status.

The problem here is because of above fact. You are using data-binding to add items to first combo in constructor and as mentioned above, the data-binding will not work there and so in the loop, Items collection of first combo is empty yet and no items will be added to second combo.

You can solve the problem using either of these options:

  • Add values directly to Items of first combo: box.Items.AddRange(MyList.ToArray());
  • Put the codes in Shown or Load event of the form.
  • Make the form visible before trying to retrieve Items of first combo. For example call this.Show(); after assigning values to DataSource of first combo. Calling this.Show(); or this.Visible = true; causes the form and all of its visible controls get Created. So the controls should be visible and should be a member of visible part of a visible form.
Comments