winform listView拖拽改变行顺序
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using CommonTool; namespace WindowsFormsApp1.FrmYwzDataMainTenance { public partial class FrmQuestionSort : Form { private string symptomCode; /// <summary> ///排序界面 /// </summary> /// <param name="symptomCode"></param> public FrmQuestionSort(string symptomCode) { InitializeComponent(); this.symptomCode = symptomCode; } private void FrmQuestionSort_Load(object sender, EventArgs e) { //填充数据 var dic = DoDataTable.GetQuestionSortBysymptomCode(this.symptomCode); if (dic == null || dic.Count == 0) { MessageBox.Show("获取数据失败"); return; } int num = 1; foreach (KeyValuePair<string, string> kv in dic) { string qCode = kv.Key; string title = kv.Value; string[] item = { num.ToString(), qCode, title }; ListViewItem listViewItem = new ListViewItem(item); listView1.Items.Add(listViewItem); num++; } int width = 0; int columnCount = listView1.Columns.Count; for (int i = 0; i < columnCount - 1; i++) width += listView1.Columns[i].Width; listView1.Columns[columnCount - 1].Width = listView1.ClientSize.Width - width; //添加事件 listView1.AllowDrop = true; listView1.ItemDrag += ListView1_ItemDrag; listView1.DragEnter += ListView1_DragEnter; listView1.DragOver += ListView1_DragOver; listView1.DragDrop += ListView1_DragDrop; listView1.DragLeave += ListView1_DragLeave; } private void ListView1_DragLeave(object sender, EventArgs e) { listView1.InsertionMark.Index = -1; } private void ListView1_DragDrop(object sender, DragEventArgs e) { int targetIndex = listView1.InsertionMark.Index; if (targetIndex == -1) return; if (listView1.InsertionMark.AppearsAfterItem) targetIndex++; ListViewItem draggedItem =(ListViewItem) e.Data.GetData(typeof(ListViewItem)); listView1.BeginUpdate(); listView1.Items.Insert(targetIndex,(ListViewItem)draggedItem.Clone()); listView1.Items.Remove(draggedItem); listView1.EndUpdate(); } private void ListView1_DragOver(object sender, DragEventArgs e) { Point ptScreen = new Point(e.X,e.Y); Point pt = listView1.PointToClient(ptScreen); ListViewItem item = listView1.GetItemAt(pt.X, pt.Y); int targetIndex = listView1.InsertionMark.NearestIndex(pt); if (targetIndex > -1) { Rectangle itemBounds = listView1.GetItemRect(targetIndex); listView1.InsertionMark.AppearsAfterItem = pt.X > itemBounds.Left + (itemBounds.Width / 2); } listView1.InsertionMark.Index = targetIndex; } private void ListView1_DragEnter(object sender, DragEventArgs e) { e.Effect = e.AllowedEffect; } private void ListView1_ItemDrag(object sender, ItemDragEventArgs e) { listView1.DoDragDrop(e.Item, DragDropEffects.Move); } } }