Thursday, February 21, 2008

Using COM Controls in .Net




Many firms have invested millions of dollars in COM. So you can't expect them to throw away COM one day and adopt .net afresh.



It is possible for .Net to inter operate with COM and use COM dlls and controls in .Net.






We are going to see how to use one of my favorite COM Control - TreeView in .Net



Create a new tab in Visual Studio 2008 .Net toolbox and give good name like COM.



Right click the tab and select Choose Item which will take you to 'Choose Toolbox items' dialog. You can see three tabs viz. .Net Framework Components, COM Components and WPF Components. Select COM Components tab and check Microsoft TreeView Control 6.0, and that will add the COM treeView to the toolbox.








First let us review the VB.Net code.
Imports MSComctlLib.TreeRelationshipConstants

Public Class Form1

Dim Nodx As MSComctlLib.Node

Private Sub Form1_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load

Nodx = AxTreeView1.Nodes.Add(, , "India",
"India")

Nodx = AxTreeView1.Nodes.Add("India",
MSComctlLib.TreeRelationshipConstants.tvwChild,
"Kerala", "Kerala")

Nodx = AxTreeView1.Nodes.Add("Kerala",
tvwChild, "Kochi", "Kochi")

Nodx = AxTreeView1.Nodes.Add("India", tvwChild,
"Karnataka", "Karnataka")
Nodx.EnsureVisible()
End Sub

Private Sub btnAdd_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnAdd.Click

Nodx =
AxTreeView1.Nodes.Add(AxTreeView1.SelectedItem,
tvwChild, txtNewNode.Text, txtNewNode.Text)
txtNewNode.Text = ""
txtNewNode.Focus()


End Sub
End Class

The VB.Net code is straight forward.

That is not the case with C#.
C# is highly strict in comparison to VB.Net.
So lets review the issues:
C# doesn't support optional parameters. In COM the value is passed by reference and there is no method overloading in COM.

C# Code

using MSComctlLib;

Node NodX;

private void Form1_Load(object sender, EventArgs e)
{
Object m = Type.Missing;
Object i = "India";
NodX = axTreeView1.Nodes.Add(ref m, ref m, ref i, ref i, ref m, ref m);

Object k = "Kerala"; Object rel = TreeRelationshipConstants.tvwChild;
NodX = axTreeView1.Nodes.Add(ref i, ref rel, ref k, ref k, ref m, ref m);

Object ka = "Karnataka";
NodX = axTreeView1.Nodes.Add(ref i, ref rel, ref ka, ref ka, ref m, ref m);
Object ko = "Kochi";
NodX = axTreeView1.Nodes.Add(ref k, ref rel, ref ko, ref ko, ref m, ref m);
NodX.EnsureVisible();
}









2 comments:

  1. Using Ajax- update panel,update progess bar... vaildation control does not work properly.How to overcome this problem

    ReplyDelete
  2. Framework Components, COM Components and WPF Components. Select COM Components tab and check Microsoft TreeView Control 6.0, and that will add the COM
    MSComctlLib.TreeRelationshipConstants

    Public Class Form1

    that no work MSComctlLib.TreeRelationshipConstants

    ReplyDelete