1
votes

I have 2 forms, let's say Form1 and Form2.

In Form1 there is a button, that shows Form2 when it's pressed, and a ListView.

In Form2 there is a textbox and a button. When the button is pressed, I want the text from the textbox to be added as an item in ListView in Form1.

private void button1_Click(object sender, EventArgs e)
{
     ListViewItem item = new ListViewItem(textBox1.Text);
     Form1.listView1.Items.Add(item);
}

I get error

"An object reference is required for the non-static field, method, or property 'project.Form1.listView1'

Any ideas?

3
You have to instantiate Form1 to be able to add items to the ListView. - Adel Khayata

3 Answers

1
votes

In your Form2 constructor get an instance of Form1 and use that to access the listbox.

0
votes

Try this;

private void button1_Click(object sender, EventArgs e)
{
     ListViewItem item = new ListViewItem(textBox1.Text);
     Form1 f1 = new Form();
     f1.listView1.Items.Add(item);
}
0
votes

Instead of breaking the OOP structure you should think about using the PropertyChangedEvent. As soon as you create an instance of Form2 bind to that event that raises in textview change.

Edit: writing via phone so samples are hard to create. Take a look at this link for some hints. http://msdn.microsoft.com/en-us/library/system.componentmodel.propertychangedeventhandler.aspx