2012-04-25 135 views
1

我试图以编程方式向表单添加未指定数量的新UserControls。每次在UserControl中包含的组合框中选择一个条目时,都会添加一个。VB.NET:SelectedIndexChanged多次触发

问题是,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) 

末次

我在一个完全丧失,什么是错的。请让我知道你是否需要更多的信息,因为我会监控这个线程,直到我或其他人知道。

回答

2

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

如果要生成用户控件后已选择从下拉列表框的东西尝试使用

ComboBox.SelectionChangeCommitted 

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

+0

即* *究竟什么我一直在寻找!这个问题在过去困扰过我很多次,我从来没有找到合适的解决方案。先生,你是英雄。 – 2012-04-28 20:58:01