C#如何将listview1的项从usercontrol移动到usercontrol的另一个listview

时间:2016-02-24 18:11:34

标签: c# user-controls listviewitem

是否有可能或有没有办法将ListViewItems从usercontrol(子)转移到另一个usercontrol(Parent)如何在没有实例的情况下将其转移到父级?因为我想从子列表视图中传输数据以传递其父项。我无法实例父级,因为父级已经显示但已禁用。当我的孩子用户控件关闭或处理时,父母将再次启用如何将我的项目从孩子移动到其父母?

P.S:Usercontrol1是Usercontrol2的父级

1 个答案:

答案 0 :(得分:0)

好的,我认为这是正确的,我最终使用了这段代码:

 private void button1_Click(object sender, EventArgs e)
    {
        string[,] name = new string[listView1.Items.Count,2];//  
        for(int i = 0; i < listView1.Items.Count; i++)       //
        {                                                    // This will insert the items from the listview to array
            name[i,0] = listView1.Items[i].Text;             //
            name[i, 1] = listView1.Items[i].SubItems[1].Text;//
        }                                                    //
        ucAddBook.pass(ref name);//called the method from parent and set name as reference in parameter
        this.Dispose();//this will trigger the parent to loop the array that i pass then insert in the listview
    }

这是来自父母的代码

    public static string[,] mylist { get; set; }// i set the array to static so if the usercontrol is already disposed the array wont get reset to null
    public void pass(ref string[,] name)        // this is where the array designated
    {
        mylist = name;
    }
    private void usercon_AddBook_ControlRemoved(object sender, ControlEventArgs e)
    {
        panel2.Enabled = true;
        for (int i = 0; i <mylist.Length/2; i++)                //  
        {                                                       //
            ListViewItem item = new ListViewItem(mylist[i, 0]); // this will insert the items from array to listview
            item.SubItems.Add(mylist[i, 1]);                    //
            listView1.Items.Add(item);                          //
        }                                                       //
    }

如果我的代码需要改进,请告诉我。感谢;

注意:我更新了for循环我将它从mylist.Length-1更改为mylist.Length / 2,因为即时通讯使用2d数组因此长度会加倍,这就是为什么我将它分成2,所以我的阵列不会超出范围。