I have a WinForms project in which I dynamically add a ComboBox (meaning I cannot access it in the designer for instance) in an initialize method in a User Control. That initialize method is executed each time I activate the form on which the User Control is located by responding to the activate event from the form. I store the ComboBox in a List on my User Control so that I can reference it later. When I press the Update button on my form, I execute a method on my User Control where I read the SelectedItem from my ComboBox that is in the List I saved during the Initialize method.
However, this only works correctly the first time I press the Update button. When I select a different value in the ComboBox and push the button again, I can see in the debugger that the SelectedItem property has not updated and is still on the previous value.
What am I missing?
How I add my ComboBox during runtime (in the Initialize method in my User Control, executed each time the form is activated)
ComboBox c_options = new ComboBox();
c_options.AutoSize = true;
c_options.Location = new Point(c_standard_label.Bounds.Right + spacing, c_standard_label.Bounds.Top);
c_options.Font = new Font("Arial", 10F, FontStyle.Regular);
c_options.DropDownStyle = ComboBoxStyle.DropDownList;
c_options.Size = new Size(c_options_panel.Width - (c_standard_label.Bounds.Right + spacing), spacing);
var bindingSource1 = new BindingSource();
bindingSource1.DataSource = _view.ComplianceOptions[i];
c_options.DataSource = bindingSource1.DataSource;
c_options_panel.Controls.Add(c_options);
// this is the list in which I store the combobox
ComplianceThresholds.Add(c_options);
How I read the SelectedItem (in the Update method in my User Control, executed when the Update button on the form is pressed)
public void UpdateAnalysisParameters(object sender, EventArgs e)
{
var temp2 = new List<string>();
foreach (var i in ComplianceThresholds)
{
// here I check the selected item, which is always the same.
temp2.Add(i.SelectedItem.ToString());
}
_view.SelectedComplianceThresholds = temp2;
}