拖放:DataGridView行“TabPage之间”

时间:2014-02-16 18:23:37

标签: c# winforms datagridview drag-and-drop tabcontrol

[已解决]我想将一些DataGridViewRows从包含在TabPage中的DataGridView拖到另一个包含在另一个TabPage中的DataGridView中。我已经设置了DataGridView的事件(How could I Drag and Drop DataGridView Rows under each other?),但我不知道如何在TabPages之间“导航”!

2 个答案:

答案 0 :(得分:2)

以下是一个简单的示例,我可以将文本从选项卡上的一个文本框拖到另一个选项卡上的另一个文本框中:

private void textBox1_MouseDown(object sender, MouseEventArgs e)
{
    textBox1.DoDragDrop(textBox1.Text, DragDropEffects.Copy | DragDropEffects.Move);
}

private void tabControl1_DragOver(object sender, DragEventArgs e)
{
    Point location = tabControl1.PointToClient(Control.MousePosition);
    for (int tab = 0; tab < tabControl1.TabCount; ++tab)
    {
        if (tabControl1.GetTabRect(tab).Contains(location))
        {
            tabControl1.SelectedIndex = tab;
            break;
        }
    }
}

private void textBox2_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.Text))
        e.Effect = DragDropEffects.Copy;
    else
        e.Effect = DragDropEffects.None;
}

private void textBox2_DragDrop(object sender, DragEventArgs e)
{
    textBox2.Text = e.Data.GetData(DataFormats.Text).ToString();
}

注意:您必须在TabControl上将AllowDrop属性设置为true,当然还要在目标控件上设置。

干杯

答案 1 :(得分:0)

我自己解决了这个问题(和@mrlucmorin):

internal void dgv_MouseDown(object sender, MouseEventArgs e)
{
     DataGridView dgv = (DataGridView)sender;
     List<DataGridViewRow> result = new List<DataGridViewRow>();
     foreach(DataGridViewRow row in dgv.SelectedRows)
     {
         result.Add(row);
     }
     dgv.DoDragDrop(result, DragDropEffects.Copy | DragDropEffects.Move);
}

private void dgv_DragEnter(object sender, DragEventArgs e)
{
     e.Effect = DragDropEffects.Copy;
}

private void dgv_DragDrop(object sender, DragEventArgs e)
{
     try
     {
          DataGridView dataGridView1 = (DataGridView)sender;
          List<DataGridViewRow> rows = new List<DataGridViewRow>();
          rows = (List<DataGridViewRow>)e.Data.GetData(rows.GetType());

          //some stuff
     }
 }