VB.NET:SelectedIndexChanged多次触发

时间:2012-04-25 22:23:21

标签: vb.net events event-handling controls selectedindexchanged

我正在尝试以编程方式向表单添加未指定数量的新UserControl。每次在UserControl中包含的ComboBox中选择一个条目时,都会添加一个。

问题是,SelectedIndexChanged事件完全不正常地触发。有时两次,有时三次等,但从来没有一次。无论我将组合框的SelectedIndex设置为-1多少次,它都会在SelectedIndex为0的情况下至少触发一次。有时,Itemselected事件会在SelectedIndexChanged事件之间多次触发。

InvoiceEntry.vb摘录:

Public Event ItemSelected As EventHandler
Private Sub cboItem_SelectedIndexChanged(sender As System.Object, _
            e As System.EventArgs) Handles cboItem.SelectedIndexChanged
    RaiseEvent ItemSelected(Me, EventArgs.Empty)
End Sub

Invoice.vb片段:

Private numEntries As Integer = 1

Public Sub invEntry1_ItemSelected() Handles invEntry1.ItemSelected
    numEntries += 1

    Dim newEntry As InvoiceEntry = invEntry1
    Dim pt As Point = newEntry.Location
    pt.Y += 30

    newEntry.Location = pt
    newEntry.Name = "invEntry" + numEntries.ToString

    pnlEntries.Controls.Add(newEntry)

End Sub

我完全不知道出了什么问题。如果您需要更多信息,请告诉我,因为我会监控这个帖子,直到我或其他人想出来。

2 个答案:

答案 0 :(得分:2)

据我所知,当你添加新的组合框时,所选索引此时正在改变(这是它第一次触发时)。每次以编程方式更改值时,它也会触发。

如果您想在用户从组合框中选择某些内容后生成控件,请尝试使用

ComboBox.SelectionChangeCommitted

http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted.aspx

答案 1 :(得分:0)

与ListView我有同样的问题。 我用了这个:

if (listview.SelectedItems.Count > 0)
{
   //do something...
}