|
今天工作中遇到一個(gè)問題,需要將一個(gè)DataGridView中的某一行拖拽到另一個(gè)DataGridView中,在網(wǎng)上搜了一遍,大多是從DataGridView拖拽到TextBox等控件,沒有拖拽到 代碼如下: gridSource的MouseDown事件: private void gridSource_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { DataGridView.HitTestInfo info = this.gridSource.HitTest(e.X, e.Y); if (info.RowIndex >= 0) { if (info.RowIndex >= 0 && info.ColumnIndex >= 0) { string text = (String)this.gridSource.Rows[info.RowIndex].Cells[info.ColumnIndex].Value; if (text != null) { this.gridSource.DoDragDrop(text, DragDropEffects.Copy); } } } } }
gridTarget的DragDrop事件: private void gridTarget_DragDrop(object sender, DragEventArgs e) { //得到要拖拽到的位置 Point p = this.gridTarget.PointToClient(new Point(e.X, e.Y)); DataGridView.HitTestInfo hit = this.gridTarget.HitTest(p.X, p.Y); if (hit.Type == DataGridViewHitTestType.Cell) { DataGridViewCell clickedCell = this.gridTarget.Rows[hit.RowIndex].Cells[hit.ColumnIndex]; clickedCell.Value = (System.String)e.Data.GetData(typeof(System.String)); //如果只想允許拖拽到某一個(gè)特定列,比如Target Field Expression,則先要判斷列是否為Target Field Expression,如下: //if (0 == string.Compare(clickedCell.OwningColumn.Name, "Target Field Expression")) //{ // clickedCell.Value = (System.String)e.Data.GetData(typeof(System.String)); //} } }
gridTarget的DragEnter事件: private void gridTarget_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; } 分類: 02 C#/.NET |
|
|