Hi all I am having 2 forms with checkedListBox . On my form1 I will select a few and click on submit where I will load form2, again on Form2 I will have a checkedListBox with the same Items as per in the first form1. Now I would like to check the form2 checkedListBox as per the form1 selected list.
I tried the following code
public class randomClass1
{
public bool IsChecked { get; set; }
public string Name { get; set; }
public randomClass1()
{
this.IsChecked = true;
Name = "name1";
}
}
My button click event on form1 is as follows
private void button1_Click(object sender, EventArgs e)
{
frmChild1 frm = new frmChild1();
List<randomClass1> lst = new List<randomClass1>();
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
lst.Add(new randomClass1());
}
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
randomClass1 obj = (randomClass1)checkedListBox1.Items[i];
if (checkedListBox1.GetItemChecked(i))
{
checkedListBox1.SetItemChecked(i, obj.IsChecked);
}
else
{
obj.IsChecked = false;
checkedListBox1.SetItemChecked(i, obj.IsChecked);
}
}
frm.loadFrom(lst); //unable to retrieve the same when I checked
//frm.loadFrom(lst);
frm.Show();
}
In form2 I tried of creating the same class but I am unable to access that class, can some one help me what should I code in form2 inorder to get the selected items
There are a number of ways to solve this problem.
First off, I’m assuming that Form1 has access to the Form2 object. If it doesn’t, something else will need to act as a middleman to get the checkstate data from Form1 to Form2.
Assuming it does, all you need is a public method like:
or however you want that to work. My quick solution is that in Form1 I’ve got a button click handler that makes a Form2, shows it and sets the list. But whatever… you just need to be able to communicate those states between the two forms. Here’s that code:
In production code I’d probably opt for a pattern like MVC and do things differently but this will work.
The idea is no different if you use your randomClass1 class rather than my
List<bool>.Obviously here I’ve made assumptions such as that both checkedlistboxes have pre-populated items and they’re in the same order, etc. etc.
You could certainly send all that data across and create the items dynamically as well. It wasn’t clear from your question which you were doing but I assumed the list was already populated with items.