0

I make a code that aims to make a combobox with an associated label. How can I get the label to show the value found in the combo box.

There is provided a combobox and a label each time you press a button, so there will be x-number of comboboxes and labels.

ArrayList cboRunList = new ArrayList();
    ArrayList labRunList = new ArrayList();
    private void button1_Click(object sender, EventArgs e)
    {
        // Tilføjer ComboBoxe
        ComboBox cboRun = new ComboBox();
        string[] s = { "", "a", "b", "c", "d", "1", "2", "3", "4" };
        cboRun.DataSource = s;
        cboRun.Location = new System.Drawing.Point(10, 10 + (20 * c));
        cboRun.Size = new System.Drawing.Size(200, 25);
        cboRunList.Add(cboRun);
        cboRun.Click += new EventHandler(cboRun_Click);
        Controls.Add(cboRun);


        // Tilføjer label
        Label labRun = new Label();
        labRun.Name = "LabDyn" + c;
        labRun.Location = new System.Drawing.Point(270, 10 + (20 * c));
        labRun.Size = new System.Drawing.Size(1000, 20);
        labRunList.Add(labRun);
        labRun.Text = "LabDyn" + c;
        Controls.Add(labRun);
        c = c + 1;
janus Mack
  • 53
  • 8

1 Answers1

2

If you want some controls to be associated and work together, You need to create a UserControl. Which is why they are for.

  • Create a user control
  • Add Combobox and Label
  • Set the required properties,
  • Wire the events and add your associated code to reflect one's change in another.

You're done with creating a UserControl. Now wherever you need this ComboBox and Label together, you'll create a instance of YourNewUserControl and add it to the parent(typically a Form).

Also give importance to gunr2171's comment. Don't use ArrayList use List<T> instead for obvious reasons.

Community
  • 1
  • 1
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Good answer, and might i suggest the parent be a flow layout panel, because it makes it so much easier to just add the controls and not worry about where you are adding them. – DidIReallyWriteThat Oct 01 '14 at 15:25