如何从其他表单访问已检查的项目?

时间:2012-11-21 19:31:05

标签: c#

我有两种形式:form1和form2。

form1包含button1listbox1,form2包含button2checkedlistbox1

点击button1时必须打开form2并检查checkedlistbox1的项目。然后点击button2,以便form2关闭,listbox1必须显示来自checkedlistbox1的已检查项目。但是我无法将选中的项目从checkedlistbox1复制到listbox1。我该怎么办,请帮忙。

1 个答案:

答案 0 :(得分:3)

因此,我们首先将此属性添加到Form2。这将是沟通的核心:

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]));
        }
    }
}

这样我们就可以从其他表单中设置所选项目(可以为项目值使用string以外的其他内容),或者从此表单中获取所选项目。

然后在Form1我们可以做到:

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]));
    }
}

当我们单击按钮时,我们创建第二个表单的实例,设置它的选定索引,向FormClosed事件添加处理程序以使用新选择更新列表框,然后显示表单。您会注意到,设置某些ListBox项的实现方式与CheckedItems的{​​{1}}方法完全相同。如果你发现自己这么做了很多,可以考虑将它重构为更通用的方法。