无法将已检查的项目checkedlistbox form1添加到listbox form2

时间:2012-11-21 13:53:54

标签: c# winforms

我有2个form form1和form2。我想在单击button2时将checkedlistbox1(form1)中的已检查项添加到listbox(form2)。我怎么能这样做

Form1中

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

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

窗体2

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);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

像这样更改Form1

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

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

表格2

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

答案 1 :(得分:0)

有一些问题。

首先,每次按下按钮,都会创建一个新表格。我想你想创建它的一个实例?

第二个问题是,您无法像这样从form2访问form1.checkedListBox1

我认为checkListBox1.CheckedItems不是字符串列表。也许你想要添加项目的文本或价值......

最好尝试这样的事情:

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;
    }
} 

窗体2

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);
        }
    }
}

我没有检查代码,但它应该是这样的......