In this case we consider the situation where there are just lines of text in listbox that we will drag.
So, we have ListBox which is named listBox1 and global variable indexOfItem to store index of the selected item of listBox1.
At first, we need to create EventHandlers that will handle mouse events.
listBox1.MouseDown += new MouseEventHandler(Form1_MouseDown);
listBox1.DragEnter += new DragEventHandler(Form1_DragEnter);
listBox1.DragDrop += new DragEventHandler(Form1_DragDrop);
First, we'll process function which is called when you click mouse button.
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
try
{
if (e.Clicks == 1 && MouseButtons == MouseButtons.Left) //if there was one left button click
{
indexOfItem = listBox1.IndexFromPoint(new Point(e.X, e.Y)); //then find out what element was clicked
if (indexOfItem >=0 && indexOfItem < listBox1.Items.Count)
{
listBox1.DoDragDrop(listBox1.Items[indexOfItem], DragDropEffects.All);//then call DoDragDrop function
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
Now, the function that is called when we release the mouse button.
private void Form1_DragEnter(object sender, DragEventArgs e)
{
try
{
if (e.Data.GetDataPresent(DataFormats.StringFormat)) // if our data is string;
e.Effect = DragDropEffects.All;
// then we'll see all DragDrop effects;
elsee.Effect = DragDropEffects.None;
//else there will be no effects and no DragDrop
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
And finally, the most important fucntion that actually drag lines.
private void Form1_DragDrop(object sender, DragEventArgs e)
{
try
{
Point newPoint = new Point(e.X, e.Y);
newPoint = listBox1.PointToClient(newPoint);
int selectedIndex = listBox1.IndexFromPoint(newPoint); //index of element on which the mouse button is released
string temp = (string)e.Data.GetData(DataFormats.Text);
if (e.Data.GetDataPresent(DataFormats.StringFormat)) //if our data is a string
{
if (selectedIndex >= 0 && selectedIndex < listBox1.Items.Count && selectedIndex > indexOfItem) //if the index of element where to insert the row is greater than index of the element which we drag
{
listBox1.Items.Insert(selectedIndex + 1, temp);
listBox1.SetSelected(selectedIndex + 1, true);
}
else if (selectedIndex >= 0 && selectedIndex < listBox1.Items.Count && selectedIndex < indexOfItem) //if the index of element where to insert the row is less than index of the element which we drag
{
listBox1.Items.Insert(selectedIndex, temp);
listBox1.SetSelected(selectedIndex, true);
}
if (indexOfItem < selectedIndex)
{
listBox1.Items.RemoveAt(indexOfItem); //now to avoid repetitions, we must remove the item that was dragged from its original position
}
else if (indexOfItem > selectedIndex)
{
listBox1.Items.RemoveAt(indexOfItem + 1);
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
That's all. Now we can do DragDrop within the same listbox.
Немає коментарів:
Дописати коментар