Tran Nam
Tran Nam

Reputation: 11

can't add checked item checkedlistbox form1 to listbox form2

I have 2 form form1 and form2. I want to add checked items from checkedlistbox1 (form1) to listbox (form2) when i click button2. How can i do that

Form1

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

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

Form2

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

    private void button2_Click(object sender, EventArgs e)
    {
        Form1 form1 = new Form1();
        foreach(string item in form1.checkedListBox1.CheckedItems)
        {
            listBox1.Items.Add(item);
        }
    }
}

Upvotes: 1

Views: 1226

Answers (2)

abc
abc

Reputation: 2437

There are some problems.

First of all, every time you press a button, you create a new Form. I think you want to create one instance of it?

The second problem is, you can't access form1.checkedListBox1 from form2 like this.

And I don't think checkedListBox1.CheckedItems is a List of strings. Maybe you want to add the text or the value of the item...

Better try something like this:

Form1

public partial class Form1 : Form
{
    Form2 form2;
    public Form1()
    {
        InitializeComponent();
        form2 = new Form2(this);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        form2.Show();
    }

    public List<string> GetCheckedItems()
    {
        return this.checkedListBox1.CheckedItems;
    }
} 

Form2

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

    public Form2(Form1 parentForm)
    {
        InitializeComponent();
        this.form1 = parentForm;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        foreach(string item in form1.GetCheckedItems())
        {
            listBox1.Items.Add(item);
        }
    }
}

I didn't check the code, but it should be something like this...

Upvotes: 0

Aram Beginyan
Aram Beginyan

Reputation: 294

Change Form1 like this

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

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

Form 2

public partial class Form2 : Form
{
    public Form2(CheckedListBox checkedListBox1)
    {
        InitializeComponent();
        foreach(string item in checkedListBox1.CheckedItems)
        {
            listBox1.Items.Add(item);
        }
    }
}

Upvotes: 1

Related Questions