1
我使用DataGridView創建窗體,我需要在此DataGridView中拖放行。在DataGridView中拖放行
它從數據庫中填充。我的代碼無法正常工作,因爲在第一次拖放之後,我無法將行拖放到正確的位置。
這是Load
形式,其中DataGridView
從數據庫
DataTable bsPeople;
Rectangle dragBoxFromMouseDown;
int rowIndexFromMouseDown;
int rowIndexOfItemUnderMouseToDrop;
private void Form1_Load(object sender, EventArgs e)
{
DataGridView1.AllowDrop = true;
bsPeople= objPeople.ReturnPeople(); // fill data from SQL Server
DataGridView1.DataSource = bsPeople;
}
填補這是拖放事件
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
if (((e.Button ==MouseButtons.Left)))
{
if (((dragBoxFromMouseDown != Rectangle.Empty)
&& !dragBoxFromMouseDown.Contains(e.X, e.Y)))
{
DragDropEffects dropEffect = DataGridView1.DoDragDrop(DataGridView1.Rows[rowIndexFromMouseDown], DragDropEffects.Move);
}
}
}
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
rowIndexFromMouseDown = DataGridView1.HitTest(e.X, e.Y).RowIndex;
if ((rowIndexFromMouseDown != -1))
{
Size dragSize = SystemInformation.DragSize;
dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width/2), e.Y - (dragSize.Height/2)), dragSize);
}
else
{
dragBoxFromMouseDown = Rectangle.Empty;
}
}
private void dataGridView1_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
Point clientPoint = DataGridView1.PointToClient(new Point(e.X, e.Y));
rowIndexOfItemUnderMouseToDrop = DataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;
if ((e.Effect == DragDropEffects.Move))
{
DataGridViewRow rowToMove = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));
object[] celldata=new object[DataGridView1.ColumnCount];
for (int col = 0; (col
<= (rowToMove.Cells.Count - 1)); col++)
{
celldata[col] = rowToMove.Cells[col].Value;
}
DataRow row = bsPeople.NewRow();
row.ItemArray = celldata;
bsPeople.Rows.InsertAt(row, rowIndexOfItemUnderMouseToDrop);
rowToMove.DataGridView.Rows.Remove(rowToMove);
}
}
}
我有一個MSDN代碼示例移動行了並通過按鈕,而不是你在找什麼,但基本邏輯可以使用幾種語言擴展方法爲vb.net和C#。無需下載,只需瀏覽代碼即可。我沒有在這裏包含代碼,因爲它使用按鈕而不是拖放。 https://code.msdn.microsoft.com/Move-rows-updown-and-987fe786 –