Download DragDropSample.zip - 36.1 KB http://www.codeproject.com/useritems/Drag_Drop_from_GridView/DragDropSample.zip
Original Article by Mr. Nauman Bhatti
Introduction
In the article, we will learn how to drag a cell's text from a DataGridView and drop it to Textbox or RichTextBox control

Using the code
In the drag operation of a text from the DataGridView cell, the following
events participate:
dataGridView1_MouseDown
This event occurs when the mouse pointer is over the control and a mouse button
is pressed. We use this event to capture the cell's text which is being dragged
from the DataGridView. The following line of code accomplishes this:
{
DataGridView.HitTestInfo info = dataGridView1.HitTest(e.X, e.Y);
if (info.RowIndex >= 0)
{
if (info.RowIndex >= 0 && info.ColumnIndex >= 0)
{
string text = (String)dataGridView1.Rows[info.RowIndex].Cells info.ColumnIndex].Value;
if (text != null)
dataGridView1.DoDragDrop(text, DragDropEffects.Copy);
}
}
}
DataGridView.HitTestInfo, Contains information, such as the row and column indexes, about a specific coordinate pair in the DataGridView control. This class cannot be inherited.
This is all that you have to write on DataGridView's events.
Drop a text on TextBox
textBox1_DragDrop
This event occurs when the mouse pointer is on the textbox control and mouse button is released. you have to typecast the data from the DragEventArgs to assign it to the text property of the textbox.
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
textBox1.Text = (System.String)e.Data.GetData(typeof(System.String));
}
}
textBox1_DragEnter
This event occurs when the mouse pointer is dragged and it enters in the
textbox. Here you have to specify the effects of the drap-drop opertaion
{
e.Effect = DragDropEffects.Copy;
}
Other then this you also have to set the "AllowDrop" property of the textbox to
"true".
Drop a text in RichTextBox
To drop a text in the RichTextBox you only have to set it's "EnableAutoDragDrop"
property to "true".
No comments:
Post a Comment