【问题标题】:Excel Controls - Delete Combo Box DynamicallyExcel 控件 - 动态删除组合框
【发布时间】:2012-09-17 12:09:26
【问题描述】:

我已在我的工作表中动态添加了一个组合框,我想在两个事件结束时动态删除该组合框 - 特别是 combobox.LostFocus 和 combobox.KeyDown 事件。

它目前适用于两种情况:

  1. 用户手动从下拉列表中选择一个项目
  2. 用户部分输入项目并自动完成其余部分的填写,然后用户按键盘上的 Enter。

如果用户输入整个文本以进行选择,然后按回车,则它不起作用。我收到消息:

COMException 未被用户代码处理:无法获取 OLEObject 类的 Name 属性

Visual Studio 指向“sheetVSTO.Controls.Remove(myBox);”行在 myBox_LostFocus 事件处理程序中作为失败的来源。

用户可以在组合框中输入整个文本并按下回车键。任何帮助将不胜感激。

这是我所拥有的(如果需要更详细的信息,请告诉我):

    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);
    }

【问题讨论】:

  • 失败的完整文本条目是否包含在自动完成源的项目列表中?还是您还需要能够添加新项目?
  • 失败的行在 myBox_LostFocus 事件处理程序中,特别是在 'sheetVSTO.Controls.Remove(myBox)'
  • 为了更好地回答您的问题,完整的文本项在自动完成源中。但是当输入一个完整的项目时,自动完成下拉菜单就会消失。

标签: c# excel controls vsto


【解决方案1】:

我找到了答案!

我将我的 2 个删除调用更改为:

myBox.BeginInvoke(new MethodInvoker(delegate { sheetVSTO.Controls.Remove(myBox); }));

【讨论】:

    猜你喜欢
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 2015-04-13
    • 1970-01-01
    • 2012-06-17
    • 2012-09-09
    • 1970-01-01
    相关资源
    最近更新 更多