I have 2 forms : Form1 , Form2 . Form1 has checkedlistbox : checkedlistbox1
All i need is when i click a button from Form2 then checkedlistbox item should be clear. From searching i found and applied this code but didn't work.
using (Form1 form1 = new Form1())
{
form1.checkedListBox1.Items.Clear();
}
but didn't work. Please suggest some ideas.
You are creating a new form, that you don't show, and are clearing the list box on that form. What you need is a reference to the form you already have opened up. So wherever you open up Form1
(from program.cs maybe?), store the reference to Form1 so that you can use that reference from form2
so call checkedListBox1.Items.Clear();
Because when you do
using (Form1 form1 = new Form1())
you are actually creating a new instance of Form1
. That's why it won't work. You need to get the current instance of Form1
.
foreach (var item in Application.OpenForms)
{
Form1 form1 = item as Form1;
if (form1 != null)
{
form1.checkedListBox1.Items.Clear();
}
}
or probably
((Form1) Application.OpenForms["Form1"]).checkedListBox1.Items.Clear();
What you did is creating a new instance of the Form1. You need to access the one that is already created (having the list filled up) then do the clear.
You must pass the instance of Form1 to Form2, if you want to access that on the currently displayed form.
If you are displaying Form2 from within Form1 in the following fashion,
Form2 form2 = new Form2();
form2.ShowDialog(this);
Then, you can use,
using (Form1 form1 = ((Form1)Owner))
{
form1.checkedListBox1.Items.Clear();
}
There are a few thing you should do:
OnClick
event on form2 form1reference.checkedListBox1.Items.Clear();
You are creating new instance of Form1 here it will not work. Use property like Owner etc. Try something like this.
var myowner = this.Owner as Form1;
myowner.checkedListBox1.Items.Clear();
检查或将您的Form1复选框的Modifys属性更改为public
in the form 1 set check box 1 modifiers to public and if form1 is already opened form2 code will be:
private void button1_Click(object sender, EventArgs e)
{
form1.checkBox1.Checked = false;
}
Make your CheckBoxList public from Form1.Designer.cs
.
Then
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.Show();
//form1.checkedListBox1.SetItemChecked(0, true);
form1.checkedListBox1.Items.Clear();
}
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.