我试图以编程方式向表单添加未指定数量的新用户控件。每次在用户控件中包含的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)
结束子
我完全失去了什么是错的。如果您需要更多信息,请告诉我,因为我将监视此主题,直到我或其他人发现它为止。
据我所知,当你添加新的组合框时,所选索引此时正在改变(这是它第一次触发时)。每次以编程方式更改值时,它也会触发。
如果要在用户从组合框中选择某些内容后生成控件,请尝试使用
ComboBox.SelectionChangeCommitted
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted.aspx
与listview我有同样的问题。我用过这个:
if (listview.SelectedItems.Count > 0)
{
//do something...
}