Reputation: 113
I have the following code that successfully drags and drops a treeview node to a textbox in a WFA:
private void _MyTreeView_ItemDrag(object sender, ItemDragEventArgs e)
{
DoDragDrop(e.Item.ToString(), DragDropEffects.Copy);
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
textBox1.Text += (System.String)e.Data.GetData(typeof(System.String));
}
}
but I wanted to be able to do a few other things with the drag and drop.
(1) If the node I'm dragging to the textbox has a Text property value of 'MyTreeNode', then the value that appears in the textbox is 'TreeNode: MyTreeNode' and not 'MyTreeNode' i.e. it adds 'TreeNode: ' at the start. How can I fix this?
(2) Is there someway I can prevent all TreeNodes at the root level from being dragged and dropped?
(3) With the code I have above, when I drag and drop a treenode the treenode text is appended to the end of the text that is already in the textbox. Am I able to add a 'drop cursor'(i dont know what you would call it) and have the treenode dropped at the position its actually dropped i.e. the position of the cursor?
Upvotes: 4
Views: 3043
Reputation: 942020
The TreeNode.ToString() method doesn't do what you hope it does, you'll have to use the TreeNode.Text property explicitly. Combining 1) and 2):
private void treeView1_ItemDrag(object sender, ItemDragEventArgs e) {
var node = (TreeNode)e.Item;
if (node.Level > 0) {
DoDragDrop(node.Text, DragDropEffects.Copy);
}
}
Your DragEnter event handler is too permissive, you allow anything to be dragged to the TextBox. But you only can handle a string, so check for that:
private void textBox1_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(typeof(string))) e.Effect = DragDropEffects.Copy;
}
And you avoid the concatenation by using a simple assignment instead of +=
private void textBox1_DragDrop(object sender, DragEventArgs e) {
textBox1.Text = (string)e.Data.GetData(typeof(string));
}
Do consider a Label instead of a TextBox if the user should not edit the text himself.
Upvotes: 3