Piyush
Piyush

Reputation: 5315

How to differentiate two instances of same form control in .net

I have 2 Treeview in one form as below.

left_treeview_node1  | right_treeview_node1 
left_treeview_node2  | right_treeview_node2 
left_treeview_node3  | right_treeview_node3
left_treeview_node4  | right_treeview_node4

here we can drag and drop left treenode on right for mapping.

now user has opened 2 instances of same form and he is dragging left_treeview_node1 from first instance and dropping it to right_treeview_node4 of another instance of same form.

so how to differentiate the another instance and stop supporting drag and drop from one instance to another instance.

are there different GUID for each instance of same form?

can we use Mutex to differentiate between 2 instances of same form?

Thanks in advance...

Upvotes: 0

Views: 256

Answers (5)

Piyush
Piyush

Reputation: 5315

Here I have used the control's HASHCODE to determine the different instance of the control like below and it worked.

in tvw1.DragDrop event

Dim draggedNode As TreeNode = Nothing draggedNode = DirectCast(e.Data.GetData(GetType(TreeNode)), TreeNode) If draggedNode Is Nothing Then Exit Sub If Not (draggedNode.TreeView.GetHashCode = tvwStagingArea.GetHashCode) Then 'do whatever you want Exit Sub End If

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941465

I'll assume you pass the TreeNode as the object to drag:

    private void treeView1_ItemDrag(object sender, ItemDragEventArgs e) {
        treeView1.DoDragDrop(e.Item, DragDropEffects.Move);
    }

Then you want to write the DragEnter event handler on the second TreeView to verify that you indeed get a TreeNode and that it came from the TreeView you expected:

    private void treeView2_DragEnter(object sender, DragEventArgs e) {
        if (!e.Data.GetDataPresent(typeof(TreeNode))) return;
        var node = (TreeNode)e.Data.GetData(typeof(TreeNode));
        if (node.TreeView == this.treeView1) {
            e.Effect = DragDropEffects.Move;
        }
    }

The object identity check will not match it the node came from another form. If you want to check that it came from the expected form instead of the expected TreeView (seems unlikely here) then write the test as if (node.TreeView.FindForm() == this).

Upvotes: 1

Trevor_G
Trevor_G

Reputation: 1331

You can also just test in the drag events to see if the form is focused. If it's not then you know the rest. Or if you really want to be sure, disable/enable drag drop on the controls when the form loses/gains focus.

Upvotes: 0

Igor
Igor

Reputation: 15893

Compare values returned by Control.FindForm - do not allow dropping if they are different for a dragged and target items.

Upvotes: 0

Striped
Striped

Reputation: 1

Use Control.Handle property which uniquely identifies a control or a form in your case.

Upvotes: 0

Related Questions