Overiew
今天我們來看一下如何實現我們的拖拽事件。
C#的拖拽
有兩個主要的事件:
DragEnter
拖拽到區域中觸發的事件
DragDrop
當拖拽落下的時候發出此事件
學習博客:https://www.cnblogs.com/slyfox/p/7116647.html
從ListBox拖拽到另一個ListBox
using System;
using System.Windows.Forms;
namespace StudyDrag
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void Init()
{
this.listBox1.AllowDrop = true;
this.treeView1.AllowDrop = true;
this.listBox2.AllowDrop = true;
}
void LoadData()
{
//加載數據
for (int i = 1; i <= 10; i++)
{
string itemValue = "有關部門" + i.ToString();
this.listBox1.Items.Add(itemValue);
}
}
private void Form1_Load(object sender, EventArgs e)
{
Init();
LoadData();
}
/// <summary>
/// 鼠標點擊的時候開始執行拖拽操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
if (this.listBox1.SelectedItem != null)
{
this.listBox1.DoDragDrop(this.listBox1.SelectedItem, DragDropEffects.Copy);
}
}
/// <summary>
/// 當拖拽完成后觸發的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBox2_DragDrop(object sender, DragEventArgs e)
{
string item = (string)e.Data.GetData(DataFormats.Text);
this.listBox2.Items.Add(item);
}
/// <summary>
/// 當拖拽進去區域后觸發的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBox2_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
}
}
這樣我們就完成了我們的拖拽事件。