D-Lef
D-Lef

Reputation: 1349

Add item in listview in Form1 from textbox in Form2 C#

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?

Upvotes: 1

Views: 3242

Answers (3)

Feri
Feri

Reputation: 1111

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

Upvotes: 1

zewa666
zewa666

Reputation: 2603

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

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98810

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

Upvotes: 0

Related Questions