2012-04-25 134 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