问题
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