0

我有两种形式:form1 和 form2。

form1 包含button1and listbox1, form2 包含button2and checkedlistbox1

当单击button1必须打开form2 并检查项目时checkedlistbox1。然后单击button2如此form2关闭并且listbox1必须显示已选中的项目来自checkedlistbox1。但是我无法将检查的项目从复制checkedlistbox1到的问题listbox1。我该怎么做,请帮忙。

4

1 回答 1

3

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.

于 2012-11-21T19:52:50.173 回答