VSTO中的错误 - 工作表中的Combobox无缘无故地向下滚动

时间:2015-05-14 15:58:42

标签: vb.net excel drop-down-menu combobox vsto

看看下面的代码。此代码非常有效,将单元组合放置在单元格A1上,为您提供项目列表。

Dim sheet As Microsoft.Office.Tools.Excel.Worksheet
Dim sheet1 As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet
sheet = Globals.Factory.GetVstoObject(sheet1)

Dim combo As New Windows.Forms.ComboBox()
'combo.AutoCompleteMode = Windows.Forms.AutoCompleteMode.SuggestAppend
combo.AutoCompleteSource = Windows.Forms.AutoCompleteSource.ListItems
combo.Items.AddRange({"test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9", "test10", "test11", "test12", "test13", "test14", "test15", "test16", "test17", "test18", "test19", "test20", "test21", "test22", "test23", "test24", "test25", "test26", "test27", "test28", "test29", "test30", "test31", "test32", "test33", "test34"})
Me.sheet.Controls.AddControl(combo, Me.sheet.Range("$A$1"), "test")

当您取消将AutoCompleteMode设置为SuggestAppend的代码行时,会出现问题。

要查看发生的错误,您需要使项目列表足够大,以便滚动显示。然后,单击箭头(打开下拉菜单)并选择下拉菜单的第一项。再做一次,滚动到最后一个元素,然后单击此元素。重复操作。

在执行此操作的第二次迭代中,您应该看到错误。当您按下鼠标按钮,更改光标下的元素时,列表会自动滚动。然后,当您松开鼠标按钮时,您选择的项目不是您想要的元素。

有人知道这个问题的解决方法吗?我使用VS2013,用VB.NET编程(你可以看到,呵呵)。

由于

1 个答案:

答案 0 :(得分:0)

问题由“jmierzej”here

解决

<强>解决方案:

我首先将所有项目添加到Dictionary对象,然后将组合框绑定到该词典。在下面的代码中,'prefill'对象是Dictionary对象,它保存组合框内容。

    'define the dictionary which will hold the values
    Dim prefill = New Dictionary(Of String, String)

    'add code here to fill Dictionary with your items.  In my case I used identical values for the key/value pair in the Dictionary

    cbox.DataSource = New BindingSource(prefill, Nothing)
    cbox.DisplayMember = "Value"
    cbox.ValueMember = "Key"