zizobiko25
zizobiko25

Reputation: 33

Populating a Combobox from CheckedListBox in another Form

I am trying to populate a Combobox in Form2 using checkeditems in Form1, however I keep getting System.Windows.Forms.CheckedListBox + CheckedItemCollection populated in my Combobox, please can you advise, Cheers.

Form1:

{
    public object checkbox
    {
        get { return this.checkedListBox2.CheckedItems; }
    }

}

In Form2

{ 
     private Form1 frm1;

     private void Form2_Load(object sender, EventArgs e)
     {
          frm1 = new Form1();
          try
          {
              foreach (object item in frm1.checkbox.ToString())
              {
                 comboBox1.Items.Add(item);
              }
          }
          catch (System.Exception excep)
          {
              MessageBox.Show(excep.Message);    
          }
     }
}

Upvotes: 0

Views: 702

Answers (1)

I.B
I.B

Reputation: 2923

You need to change your foreach loop :

try
{
    foreach (object item in frm1.checkbox)
    {
        comboBox1.Items.Add(item);
    }
}
catch (System.Exception excep)
{
    MessageBox.Show(excep.Message);
}

You also have to change your return statement because foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

public CheckedListBox.CheckedItemCollection checkbox
{
    get { return this.checkedListBox1.CheckedItems; }
}

Also you need to pass your Form1 to the other Form to get the information. Wherever you're creating your second form pass the current form

Form2 form2 = new Form2(this);
form2.Show();

Then your Form2 would look like this

private Form1 frm1;

public Form2(Form1 frm1)
{
    InitializeComponent();
    this.frm1 = frm1;
    try
    {
        foreach (object item in frm1.checkbox)
        {
            comboBox1.Items.Add(item);
        }
    }
    catch (System.Exception excep)
    {
        MessageBox.Show(excep.Message);
    }
}

You could also just pass the CheckedItems list at the place of the whole form.

Upvotes: 1

Related Questions