Passing listBox to a new form

痴心易碎 提交于 2019-12-25 17:02:01

问题


I have a problem with my constructor. I got it set up like this:

Form1:

private void button10_Click(object sender, EventArgs e)
{
    var form2 = new Form2(listBox1);
    form2.Show();
    this.Hide();
}  

Form2:

public Form2(ListBox listBox)
{
    InitializeComponent();
    listBox1.Items=listBox.Items;
} 

I just want to send my data from listBox on the Form1 to my Form2 listBox but it's giving me this error:

Property or indexer 'System.Windows.Forms.ListBox.Items' cannot be assigned to -- it is read only.


回答1:


You could use the answer from Sampath, which is completely correct. But for readability and shorter code, you can use the ListBox.ObjectCollection.AddRange Method:

public Form2(ListBox listBox)
{
    InitializeComponent();
    listBox1.Items.AddRange(listBox.Items);
}



回答2:


listBox.Items is read only property. You need to use listBox.Items.Add() or AddRange() method.

//From form1 pass only your listbox items.
    private void button10_Click(object sender, EventArgs e)
        {

            var form2 = new Form2(listBox1.Items);
            form2.Show();
            this.Hide();
        }


//In your form2 you can use AddRange()
    public Racun(ListBox.ObjectCollection Items)
        {
            InitializeComponent();      

            listBox1.Items.AddRange(items);

        } 


来源:https://stackoverflow.com/questions/20519089/passing-listbox-to-a-new-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!