0

form1とform2の2つのフォームがあります。

form1にはとが含まれbutton1listbox1form2にはとが含まれbutton2ますcheckedlistbox1

クリックすると、button1開く必要があり、のform2 項目を確認する必要がありますcheckedlistbox1。次に、[閉じた状態]をクリックbutton2して、からチェックされたアイテムを表示する必要があります。しかし、チェックした項目をからにコピーできないという問題。どうすればそれができますか、助けてください。form2listbox1checkedlistbox1checkedlistbox1listbox1

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 に答える