简体   繁体   中英

C# Adding array list values to combo box from one form to another

I would like to take the values of an array list taken from a seperate form and add them to a combobox on another form. I have tried this in form2.

foreach (string fname in newname)
{
    form1.comboBox1.Items.Add(fname);
}

but it doesn't send the values to the combo box. Now if I add this on form1

base.AddOwnedForm(form2)

and this on form2

Form1 form1=(Form1)this.Owner

it works but form1 will hide itself and also won't close when you click on the "X" button. (this seems to be an inherited property of form2).

Any help would be great!

I'm not sure if this is what you need it to be. I hope it is:). I'm learning C#+winforms so i have treated your question as an exercise.

I have created two simple forms (all controls default naming)

简单的表格

First form code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 newForm = new Form2(this);
        newForm.Show();
    }

    public void UpdateCombo(List<String> newName)
    {
        comboBox1.Items.Clear();
        foreach (string fname in newName)
        {
            comboBox1.Items.Add(fname);
        }
        comboBox1.SelectedIndex = 0;
    }
}

Second form code:

public partial class Form2 : Form
{
    List<String> newName;
    Form1 parent;

    public Form2(Form1 parentIn)
    {
        parent = parentIn;
        InitializeComponent();
    }

    void UpdateList()
    {
        newName = new List<String>();
        for (int i = 1; i <= numericUpDown1.Value; i++)
        {
            if (i == 1)
                newName.Add("1 duck");
            else
                newName.Add(i.ToString() + " ducks");
        }
    }

    private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        UpdateList();
        parent.UpdateCombo(newName);
    }
}

I hope that code is self explanatory, if not feel free to ask. Also it will be better if someone more experienced than me would check and approve it.

it is very easy when sending things from parent to child. As you head in the other direction, you are often better to set up "event handling" that allows the value to be "passed back".

I am not sure this is the "best" tutorial, but it covers "event handling" using delegates to pass information between forms: http://www.codeproject.com/KB/cs/PassDataWinForms.aspx . I think it would be a good place to start to understand how event handling works when you code it yourself rather than rely on double clicking a form element in the designer goodness.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM