Hi,
I'm having difficulties populating the right combobox when I
generate several combobox' at runtime. I've got a windows forms
application, where the form consists of a button and a FlowLayoutPanel.
By clicking the button, a control combination consisting of a label and
two combobox' are added to the Form (to the FlowLayoutPanel). The code
so far is given below:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms;
namespace WindowsFormsApplication1 { public partial class Form1 : Form { public int counter; public ComboBox combB; public string[] combValuesShip; public string[] combValuesCar; public string[] combValuesAirPlane; public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { AddNewComboboxLine(); }
private void AddNewComboboxLine() { counter++; Label label = new Label(); label.Text = "Label " + counter; ComboBox combA = new ComboBox(); string[] combAValues = new string[] { "Ship", "Car", "AirPlane" }; combA.Items.AddRange(combAValues); combB = new ComboBox(); combA.SelectedIndexChanged += new EventHandler(this.combAChange);
label.Name = "label" + counter.ToString(); combA.Name = "combA" + counter.ToString(); combB.Name = "combB" + counter.ToString();
flowLayoutPanel1.Controls.Add(label); flowLayoutPanel1.Controls.Add(combA); flowLayoutPanel1.Controls.Add(combB);
combValuesShip = new string[] { "Ferry", "OilTanker", "ContainerVessel" }; combValuesCar = new string[] { "Toyota", "Lada", "Ferrari" }; combValuesAirPlane = new string[] { "Boeing", "Airbus", "Sailplane" };
}
private void combAChange(object sender, EventArgs e) { MessageBox.Show(((ComboBox)sender).Name); }
private void Form1_Load(object sender, EventArgs e) {
}
} }
|
the
first combobox in each control combination (combA) is populated with
"Ship", "Car", "AirPlane". So far so good. The problem is getting
combobox combB to be populated with respective values. I can always add
something like this under the eventhandler for combobox combA:
private void combAChange(object sender, EventArgs e) { ComboBox currentCombobox = (ComboBox)sender; string lastChar = currentCombobox.Name.Substring(currentCombobox.Name.Length - 1, 1); if (lastChar == "1") { combB.Items.Clear(); combB.Items.AddRange(combValuesShip); }
if (lastChar == "2") { combB.Items.Clear(); combB.Items.AddRange(combValuesCar); }
if (lastChar == "3") { combB.Items.Clear(); combB.Items.AddRange(combValuesAirPlane); }
}
|
This
works fine if i add one control combination at a time and select the
values in the combobox' before adding new. However, editing a previous
added combobox is now not possible. I.e. if i have added three lines
(each with a label and two combobox'), but now want to change values in
the first line, this is not possible.
Any suggestinons would be highly appreciated
-Amund