MapControl控件AddLayer出现错误-引发类型为“System.Windows.Forms.AxHost+InvalidActiveXStateException”的异常
出错代码:
AxMapControl pMptrl = new AxMapControl(); //add data string mdbPath = string.Format("{0}\\line.mdb", Application.StartupPath); IWorkspaceFactory pWFS = new AccessWorkspaceFactoryClass(); IWorkspace pWS = pWFS.OpenFromFile(mdbPath, 0); if (pWS != null) { IFeatureWorkspace pFWK = pWS as IFeatureWorkspace; IFeatureClass pFC = pFWK.OpenFeatureClass("ZXLine"); IFeatureLayer pFlyr = new FeatureLayerClass(); pFlyr.FeatureClass = pFC; pMptrl.AddLayer(pFlyr as ILayer); m_FeatureLayer = pFlyr; }
错误原因是未将控件添加至窗体并注册初始化,改为如下即可:
Form f = new Form(); AxMapControl pMptrl = new AxMapControl(); ((System.ComponentModel.ISupportInitialize)(pMptrl)).BeginInit(); f.Controls.Add(pMptrl); ((System.ComponentModel.ISupportInitialize)(pMptrl)).EndInit();