Hi,
First, you need to set AllowDrop property of the two datagridview to true.
Assume form1 has a datagridview control named dataGridView1, form2 has a DataGridView control named dataGridView2.
We need to drag rows of datagridView2 to datagridview1.
In form2, we need to handle some event of datagridview2. I would like to use mousemove event to drag. If you click one cell use MouseButton.Left, this cell will get selected, and this will clear the previous selection. So you will only get one cell selected. To keep multiple rows selected when you drag, it will be easy using MouseButton.Right. Then keep the selected rows value in a collection. You need to expose the value collection to form1 in order to add the value to form1.datagridview1.
The following is an example. Not perfect but can give you a hint.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Rows.Add("11", "11");
dataGridView1.Rows.Add("11", "11");
dataGridView1.AllowDrop = true;
dataGridView1.DragDrop += new DragEventHandler(dataGridView1_DragDrop);
dataGridView1.DragOver += new DragEventHandler(dataGridView1_DragOver);
}
private void dataGridView1_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
Form2 f2;
private void button1_Click(object sender, EventArgs e)
{
f2 = new Form2(this);
f2.Show();
}
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Effect == DragDropEffects.Move)
{
// Only add rows.
//If you need insert the row where mouse down, you need use dataGridView1.HitTest method to detemine the index.
//please refer to the FAQ.
for (int i = f2.arrmove.Count - 1; i >= 0; i--)
{
ArrayList rowvalue = (ArrayList)f2.arrmove[i];
dataGridView1.Rows.Add(rowvalue[0], rowvalue[1]);
}
f2.removeRow();
}
}
}
Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.