VB.NET: SelectedIndexChanged firing multiple times

丶灬走出姿态 提交于 2019-12-08 08:22:47

问题


I am trying to programmatically add an unspecified amount of new UserControls to a form. One will be added every time an entry is selected in a ComboBox contained within the UserControl.

Problem is, the SelectedIndexChanged event fires completely erratically. Sometimes twice, sometimes 3 times, etc., but never just once. No matter how many times I set the combobox's SelectedIndex to -1, it fires at least once with a SelectedIndex of 0. Sometimes the Itemselected event fires multiple times inbetween SelectedIndexChanged events.

InvoiceEntry.vb snippet:

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 snippet:

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

I'm at a complete loss as to what is wrong. Please let me know if you need more information, as I will be monitoring this thread until I or someone else figures it out.


回答1:


As far as I know, when you add new combo box the selected index is changing at this time (this is when it triggers first time). It will also trigger every time you programatically change a value.

If you want to generate controls after user has selected something from the combo box try using

ComboBox.SelectionChangeCommitted

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




回答2:


with listview i had same problem. i used this:

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


来源:https://stackoverflow.com/questions/10324679/vb-net-selectedindexchanged-firing-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!