拖动项目并将其添加到ListView

时间:2013-01-22 15:20:30

标签: c# winforms listview treeview

我有一个包含3组的ListView。 我将一个项目从TreeView拖到ListView:

private void listViewDemo_DragDrop(object sender, DragEventArgs e)
{
    if (!is_listview) //treeview item
    {
        //get a text of a draged item
        string str = e.Data.GetData(DataFormats.Text).ToString();
        //get information about hovered item
        ListViewHitTestInfo hit_info =  listViewDemo.HitTest(listViewDemo.PointToClient(new Point(e.X, e.Y)));
        //check position - must be on an item
        if (hit_info.Location == ListViewHitTestLocations.None) return;
        ListViewItem prev_item = hit_info.Item;
        ListViewGroup group = prev_item.Group;
        int idx = prev_item.Index;
        //create a new key
        Guid key = Guid.NewGuid();
        string item_key = key.ToString();
        //create a new item
        //option 1
        group.Items.Add(listViewDemo.Items.Insert(idx,item_key, str, ""));
        //option2
        //group.Items.Insert(idx,listViewDemo.Items.Insert(idx, item_key, str, ""));
    }
}

我希望添加一个项目来代替尖头项目,但是任何选项都会在组的末尾添加元素。 如何在鼠标悬停的位置添加项目?

1 个答案:

答案 0 :(得分:1)

假设您想要将项目放在鼠标指针的项目之前...(这有点暴力,但它有效)。

我还想注意你的原始代码是在整个列表中找到热点项目的索引。我添加了IndexOf调用以从组中获取它。

            if (!is_listview) //treeview item 
            {
                //get a text of a dragged item 
                string str = e.Data.GetData(DataFormats.Text).ToString(); 
                //get information about hovered item 
                ListViewHitTestInfo hit_info = listView1.HitTest(listView1.PointToClient(new Point(e.X, e.Y))); 
                //check position - must be on an item 
                if (hit_info.Location == ListViewHitTestLocations.None) return; 
                ListViewItem prev_item = hit_info.Item; 
                ListViewGroup group = prev_item.Group;
                int idx = group.Items.IndexOf(prev_item);
                //create a new key 
                Guid key = Guid.NewGuid(); 
                string item_key = key.ToString(); 
                //create a new item 
                //option 1 
                List<ListViewItem> list = new List<ListViewItem>();
                while(group.Items.Count > 0)
                {
                    ListViewItem lvi = group.Items[0];
                    listView1.Items.Remove(lvi);
                    list.Add(lvi);
                }

                group.Items.Clear();
                ListViewItem item = new ListViewItem(str, "");
                item.Name = item_key;
                list.Insert(idx, item);
                foreach (ListViewItem i in list)
                {
                    listView1.Items.Add(i);
                    group.Items.Add(i);
                }
            }