Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

c# - How can I copy combobox contents programmatically?

I've got this code:

private void FormMain_Shown(object sender, EventArgs e)
{
    ComboBox cmbx;
    foreach (Control C in this.Controls)
    {
        if (C.GetType() == typeof(ComboBox))
        {
            cmbx = C as ComboBox;
            //cmbx.Items.AddRange(cmbxRow0Element0.Items); <= illegal
            object[] obj = new object[cmbxRow0Element0.Items.Count];
            cmbxRow0Element0.Items.CopyTo(obj, 0);
            cmbx.Items.AddRange(obj);
        }
    }
}

...but it doesn't work - I have several combo boxes on a tabPage on a tabControl on a Form, with cmbxRow0Element0 populated with items at design time. The above attempt to copy its items to all the other comboboxes fails, though.

UPDATE

This is the code I now have, and it still doesn't work:

public FormMain()
{
    InitializeComponent();

    for (int i = 0; i < 10; i++)
    {
        this.cmbxRow0Element0.Items.Add(String.Format("Item {0}", i.ToString()));
    }
    foreach (Control C in this.Controls)
    {
        ComboBox cmbx = null;

        // The & test ensures we're not just finding the source combobox
        if ((C.GetType() == typeof(ComboBox)) & ((C as ComboBox) != this.cmbxRow0Element0))
            cmbx = C as ComboBox;
        if (cmbx != null)
        {
            foreach (Object item in cmbxRow0Element0.Items)
            {
                cmbx.Items.Add(item);
            }
        }

    }
}

Perhaps it's something to do with the comboboxes being on tab pages on the tab control?

UPDATE 2

A breakpoint on the first line below is reached, but the second line is never reached:

if ((C.GetType() == typeof(ComboBox)) & ((C as ComboBox) != this.cmbxRow0Element0))
   cmbx = C as ComboBox;

UPDATE 3

The problem was the "find" was not being specific enough - the particular tabPage has to be specified. For more details, see this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

var items = cmbxRow0Element0.Items.OfType<object>().ToArray();

foreach (ComboBox c in this.Controls.OfType<ComboBox>())
{
     c.Items.AddRange(items);
}

If you are using tabControl as a container, then it means your comboboxes aren't direct child element of your Form.So you need to access Control collection of the container which is the tabControl. You can do that using this.NameOfYourTabControl.Controls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...