So we'll start by adding this property to Form2
. It will be the meat of the communication:
public IEnumerable<string> CheckedItems
{
get
{
//If the items aren't strings `Cast` them to the appropirate type and
//optionally use `Select` to convert them to what you want to expose publicly.
return checkedListBox1.SelectedItems
.OfType<string>();
}
set
{
var itemsToSelect = new HashSet<string>(value);
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetSelected(i,
itemsToSelect.Contains(checkedListBox1.Items[i]));
}
}
}
This will let us set the selected items (feel free to use something other than string
for the item values) from another form, or get the selected items from this form.
Then in Form1
we can do:
private void button1_Click(object sender, EventArgs e)
{
Form2 other = new Form2();
other.CheckedItems = listBox1.SelectedItems.OfType<string>();
other.FormClosed += (_, args) => setSelectedListboxItems(other.CheckedItems);
other.Show();
}
private void setSelectedListboxItems(IEnumerable<string> enumerable)
{
var itemsToSelect = new HashSet<string>(enumerable);
for (int i = 0; i < listBox1.Items.Count; i++)
{
listBox1.SetSelected(i , itemsToSelect.Contains(listBox1.Items[i]));
}
}
When we click the button we create an instance of the second form, set it's selected indexes, add a handler to the FormClosed
event to update our listbox with the new selections, and then show the form. You'll note the implementation of th emethod to set teh ListBox
items is of exactly the same pattern as in CheckedItems
's set
method. If you find yourself doing this a lot consider refactorizing it out into a more general method.