2表格 - Combobox + ListView

时间:2016-06-03 12:52:34

标签: c# winforms

我正在尝试传递组合框(form2)的listview(form1)但是无效。

Form2代码:

private void add_citacao_Load(object sender, EventArgs e)
{
    Form_Principal frm_prin = new Form_Principal();
    for (int i = frm_prin.listView1.Items.Count - 1; i >= 0; i--)
        comboBox1.Items.Add(frm_prin.listView1.Items[i].Text);
}

Form1代码:

private void barButtonItem40_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
    add_citacao add_cit = new add_citacao();
    add_cit.Show();
}

上面的代码应该将form1中的listview的值传递给form2的组合框。

没有错误消息;

1 个答案:

答案 0 :(得分:2)

视频元素(例如组合和列表框)永远不应该传递,你应该做的是传递控件正在显示的类

因此,如果您有一个Observable集合或其他具有要通知事件的对象已更改为集合,您可以调用表单上的代码来更新自己

class form1
{
    public ObservableCollection<string> MyList{ get; }= new ObservableCollection<string>();
    public form1()
    {
        MyList.CollectionChanged += onCollectionChanged ;
        form2.MyList = MyList;
        form2.Initialise();
    }

    private void onCollectionChanged (object sender,CollectionChangedEventArg args)
    {
         //update control on form1
    }
    private void AddItemToList(string item)
    {
         MyList.Add(item);
         //this will then raise a CollectionChanged event in both form1 and 2 (and anything else that is listerning to the event) allowing both to automatically add the new item in the control on themselves
    }
}
class form2
{
    public ObservableCollection<string> MyList{ get; set; }
    public void Initialise()
    {
        comboBox1.Items.Clear();
        comboBox1.Items.AddRange(MyList);
        MyList.CollectionChanged += onCollectionChanged ;//leave out if you don't need this form to monitor changes
    }

    private void onCollectionChanged (object sender,CollectionChangedEventArg args)
    {
         //update control on form2
    }
}