VB.Net如何防止列表框在加载时触发selectedindexchanged selectedvaluechanged

时间:2015-02-18 01:22:30

标签: vb.net listbox

帮助,当我将数据源设置为列表框时,它会触发selectedindexchanged和selectedvaluechanged。如何防止这种情况,因为这会将我的值始终重置为第一个项目

Dim SQLString As String
Dim dt As New DataTable
Dim Properties As New Properties
SQLString = "select v.attributevalue,v.value"
SQLString += " from Table "
SQLString += " Where v.attributename ='new_vehicle'"
SQLString += " order by v.value"
getDataBySQL(SQLString, dt)
lstCategory.ValueMember = "attributevalue"
lstCategory.DisplayMember = "value"
lstCategory.DataSource = dt
Dim i As Integer = ReadDataFromDatabase
If i <> 0 Then
    lstCategory.SelectedValue = i
End If
Private Sub lstCategory_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCategory.SelectedIndexChanged
End Sub
Private Sub lstCategory_SelectedValueChanged(sender As Object, e As EventArgs) Handles lstCategory.SelectedValueChanged
    SetDataToDatabase(lstCategory.SelectedValue.ToString)
End Sub

当我将valuemember设置到列表框时,它会触发selectedvaluechanged。

基本上我想读取数据库值,所以当我加载列表框时,它将所选值切换到数据库中的值

变量i是我想要的selectedValue。

1 个答案:

答案 0 :(得分:2)

通常,当我开发一个应用程序时,我将创建一个名为IsLoading的布尔变量,默认情况下将其设置为false。我会在任何可能加载数据的代码之前将其标记为true,并在完成时将其标记为false。在大多数情况下,这是在我的页面加载中。

Private Sub Form_Main_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    IsLoading = True

    'Code to load my data goes here

    IsLoading = False

End Sub

然后我会将它添加到我的下拉列表中:

Private Sub lstCategory_SelectedValueChanged(sender As Object, e As EventArgs) Handles lstCategory.SelectedValueChanged
    If Not IsLoading Then
        SetDataToDatabase(lstCategory.SelectedValue.ToString)
    End If
End Sub

因此,IsLoading标志为false,代码将被允许运行。

希望这有帮助。