Dynamically adding ActiveX in C# an equivalent for VBControlExtender

by Mauricio Rojas, on Nov 13, 2019 3:44:44 PM

In VB6, you need VBControlExtender object for dynamically adding a control to the Controls collection using the Add method.
For example for adding a MSFlexGrid dynamically to a form you have to first create a VBControlExtender variable.
Option Explicit   
Dim WithEvents dynamicFlexGrid As VBControlExtender

Then you are ready to assign MSFlexGrid control to the VBControlExtender variable and add it on to the Form's controls collection using Add method

Set dynamicFlexGrid = Controls.Add("MSFlexGridLib.MSFlexGrid.1", ,"FlexGrid1")

With "dynamicVSFlexGrid.object" you can access the FlexGrid object and it's properties/ methods

   With dynamicFlexGrid.object  
For r = 1 To .Rows - 1
For c = 1 To .Cols - 1
.TextMatrix(r, c) = "r" & r & "c" & c
dynamicFlexGrid.Height = 300
dynamicFlexGrid.Width = 300

dynamicFlexGrid.Visible = True
VBControlExtender object's ObjectEvent event could be also used in VB6 to dynamically add events. But we will let that for another post.
So now. How can we migrate that to C# with a helper like
namespace UpgradeHelpers
    public class AxControl : AxHost
        public AxControl(string strCLSID) : base(strCLSID)

    public static class ControlExtenderHelper
        public static AxHost AddExtended(this System.Windows.Forms.Control.ControlCollection controls, Type controlType, string controlName)
            var newControl = new AxControl(controlType.GUID.ToString());
            newControl.Name = controlName;
            return newControl;
        public static AxHost AddExtended(this System.Windows.Forms.Control.ControlCollection controls, string progId, string controlName)
            Type type = Type.GetTypeFromProgID(progId, true);
            return AddExtended(controls, type, controlName);

With the helper, you can just add an using statement to include the extension method. 
using UpgradeHelpers;
And the VB6 code mentioned before can then be migrated to:
        AxHost dynamicVSFlexGrid;

      private void button1_Click(object sender, EventArgs e)
          dynamicFlexGrid = Controls.AddExtended("MSFlexGridLib.MSFlexGrid.1", "FlexGrid1");
          dynamic dynamicFlexGrid_object = dynamicFlexGrid.GetOcx();
          for (int r = 1; r <= dynamicFlexGrid_object.Rows - 1; r++)
              for (int c = 1; c <= dynamicFlexGrid_object.Cols - 1; c++)
                  dynamicFlexGrid_object.TextMatrix[r, c] = "r" + r + "c" + c;
          dynamicFlexGrid.Height = 300;
        dynamicFlexGrid.Width = 300;
        dynamicFlexGrid.Visible = true;



Subscribe to Mobilize.Net Blog