I am trying to add items in listbox on WinForm1 from selected items of listview from WinForms2 but the items are not getting added in listbox.
below is the code which i am using
WinForm1:
public void setsrc( ListViewItem src )
{
Listbox1.Items.Add(src.Text);
}
Winform2:
WinForm1 fMain = new WinForm1();
private void AddItemsButton_Click(object sender, EventArgs e)
{
foreach (ListViewItem src in listView1.CheckedItems)
{
fMain.setsrc(src);
}
}
I tried below code also in form2
WinForm1 fMain = new WinForm1();
private void AddItemsButton_Click(object sender, EventArgs e)
{
foreach (ListViewItem src in listView1.CheckedItems)
{
fMain.Listbox1.Items.Add(src.Text); //The modifier is set to internal of Listbox1
}
}
I tried to check by applying breakpoints. The weird thing is the value are coming in both the conditions but its not getting listed in listbox1. There is something like the Form1's controls are not getting updated.
Please help me on this.
The problem is you are declaring a new instance of WinForm
in your Form2. Of course you won't see anything. You need to create a reference to WinForm1
when you create your Form2 object.
One way you can do this is through the constructor
class Form2
{
private WinForm1 form;
public Form2(WinForm1 form)
{
this.form = form;
}
}
then, somewhere in your WinForm1
when you create Form2
.
Form2 form = new Form2(this);
form.Show();
And please, use meaningful names for your objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.