从SQL填充ListBox仅包含条件的项目(第一个字符)

时间:2014-03-14 11:46:45

标签: sql vb.net listbox conditional-statements

我已设法将所有项目放在ListBox中,也定义了第一个字符kto,如何仅将List列中的值插入Listbox以该字符kto开头的。

提到kto是从0到9的值,总是一个数字。

        Dim SqlSb As New SqlConnectionStringBuilder()
    SqlSb.DataSource = ".\sqlexpress"
    SqlSb.InitialCatalog = "Konta"
    SqlSb.IntegratedSecurity = True

    Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
        SqlConn.Open()
        Dim cmd As SqlCommand = SqlConn.CreateCommand()
        cmd.CommandText = "SELECT List FROM Konta"
        Dim kto = Left(Label1.Text, 1)
        'Label3.Text = kto
        Using reader As SqlDataReader = cmd.ExecuteReader
            While (reader.Read())
                Me.ListBox1.Items.Add(reader("LIST"))
            End While

        End Using
        SqlConn.Close()

    End Using

2 个答案:

答案 0 :(得分:2)

试试这个

Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True

Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
    SqlConn.Open()
    Dim cmd As SqlCommand = SqlConn.CreateCommand()
    Dim kto = Left(Label1.Text, 1)
    cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
    ListBox1.Items.Clear
    Using reader As SqlDataReader = cmd.ExecuteReader
        While (reader.Read())
            Me.ListBox1.Items.Add(reader("LIST"))
        End While

    End Using
    SqlConn.Close()

End Using

答案 1 :(得分:0)

在你的while循环中,在列表框中添加项目之前,请检查阅读器的日期类型(“LIST”),并仅在匹配所需类型时添加它。

您可以使用以下代码检查类型:

reader.GetFieldType(0)