我动态地在工作表中添加了一个组合框,我希望在两个事件结束时动态删除组合框 - 特别是combobox.LostFocus和combobox.KeyDown事件。
目前适用于两种情况:
如果用户键入select的整个文本,则无效,并按Enter键。我收到了消息:
用户代码无法使用COMException:无法获取OLEObject类的Name属性
Visual Studio指向'sheetVSTO.Controls.Remove(myBox);'行在myBox_LostFocus事件处理程序中作为失败的来源。
用户显示能够将整个文本输入组合框并按Enter键。任何帮助将不胜感激。
这就是我所拥有的(如果需要更详细的话,请告诉我):
private void AddComboBox(String[] list)
{
Excel.Worksheet sheet = Globals.ThisAddIn.Application.ActiveSheet;
Microsoft.Office.Tools.Excel.Worksheet sheetVSTO = Globals.Factory.GetVstoObject(sheet);
Excel.Range cell = Globals.ThisAddIn.Application.ActiveCell;
Microsoft.Office.Tools.Excel.Controls.ComboBox myBox= new Microsoft.Office.Tools.Excel.Controls.ComboBox();
myBox.Name = "button1";
myBox.Items.AddRange(list);
myBox.KeyDown += new KeyEventHandler(myBox_KeyDown);
myBox.LostFocus += new EventHandler(myBox_LostFocus);
myBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
myBox.AutoCompleteSource = AutoCompleteSource.ListItems;
myBox.Focus();
Microsoft.Office.Tools.Excel.ControlSite myBoxControl = sheetVSTO.Controls.AddControl(myBox, cell, boxName);
}
void myBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Enter)
{
Microsoft.Office.Tools.Excel.Controls.ComboBox myBox = sender as Microsoft.Office.Tools.Excel.Controls.ComboBox;
Excel.Worksheet sheet = Globals.ThisAddIn.Application.ActiveSheet;
if (myBox.SelectedIndex > -1)
{
Microsoft.Office.Tools.Excel.Worksheet sheetVSTO = Globals.Factory.GetVstoObject(sheet);
sheetVSTO.Controls.Remove(myBox);
}
}
}
void myBox_LostFocus(object sender, EventArgs e)
{
Microsoft.Office.Tools.Excel.Controls.ComboBox myBox = sender as Microsoft.Office.Tools.Excel.Controls.ComboBox;
Excel.Worksheet sheet = Globals.ThisAddIn.Application.ActiveSheet;
Microsoft.Office.Tools.Excel.Worksheet sheetVSTO = Globals.Factory.GetVstoObject(sheet);
sheetVSTO.Controls.Remove(myBox);
}
答案 0 :(得分:0)
我找到了答案!
我更改了对此的2次删除调用:
myBox.BeginInvoke(new MethodInvoker(delegate { sheetVSTO.Controls.Remove(myBox); }));