Add dynamically created command to dynmically created menu

Discussion created by cpicciri on Aug 18, 2010
Latest reply on Aug 19, 2010 by amay_uk
Hi everyone,

From an existing custom menu on a custom toolbar called Data, I am trying to create a structure like this and do it all on the fly at run time:

    |           |----Command1
    |           |----Command2
    |           |----Command1
    |           |----Command2

Thanks to LOTS of help from the forums, I have been able to create the menus and sub-menus on the fly with no problems but now I am stuct trying to do the same with the commands.

In the example above, if I add an existing ArcMap or custom command previously created to Command1 in Submenu1, the code works fine. If I try to add a new instance of an existing command, the code crashes trying to give it a new UID with an error of, "Value does not fall within the expected range."

        internal static void PopulateDataSubMenu(ICommandBar pMenu, string entitySetName)
                OleDbConnection dataConnection = new OleDbConnection();
                dataConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                                  "Data Source=\\\\ad.sfwmd.gov\\dfsroot\\data\\err_gis\\applications\\dev\\mdb\\rimGISLibDatabase\\mdb\\GISLIBFeaterClassName1.mdb";

                OleDbCommand dataCommand = new OleDbCommand();
                dataCommand.Connection = dataConnection;
                dataCommand.CommandText = "SELECT distinct(Order1ClassName) " +
                                          "FROM qryorder1 " +
                                          "WHERE Order1SetName = '" + entitySetName + "'";

                OleDbDataReader dataReader = dataCommand.ExecuteReader();

                object idx = 0;
                int counter = 0;
                while (dataReader.Read())
                    string className = dataReader.GetString(0);
                    idx = counter;
                    CmdTest2 cmdTest3 = new CmdTest2(entitySetName + " - " + className, entitySetName, className);
                    UID uid = new UIDClass();
                    uid.Value = cmdTest3;    <---CRASH HERE      
                    pMenu.Add(uid, ref idx);

            catch (Exception ex)

In the code above, CmdTest2 is a command created using the ESRI BaseCommand template and I am passing it a couple of parameters so that I can use the same command to load different datasets.

Does anyone know how what is going on and how I can fix this?