在vb.net中使用带有SQL查询语句的select case条件

时间:2016-06-12 11:03:06

标签: vb.net

我尝试将select case语句与SQL语句一起使用 当lbl1.text等于1然后x =“column1”时,我有4列,并将此值放在SQL语句中 当我尝试这段代码时

 Dim x As String
    Select Case lbl1.Text
        Case 1
            x = "column1"
        Case 2
            x = " column2"
        Case 3
            x = " column3"
        Case 4
            x = " column4"
            DGV1.Columns.Clear()
            Dim dt As New DataTable
            dt.Clear()
            DGV1.Visible = True
            Dim comm2 As New SqlCommand
            comm2.CommandText = Nothing
            DGV1.Refresh()
            comm2.CommandText = "select first_name,last_name,age from students where " + x + "=" + "yes" + ""
            comm2.Connection = sqlconn
            sqlconn.Open()
            dr2 = comm2.ExecuteReader
            dt.Load(dr2)
            DGV1.AutoGenerateColumns = True
            DGV1.DataSource = dt
            DGV1.Refresh()
            sqlconn.Close()
            DGV1.Visible = True
            comm2.Dispose()
    End Select

lbl1.text = 1或2或3 时,它不运行SQL语句但是当 lbl1.text = 4 时它运行SQL语句 任何人都可以帮助我这个代码

1 个答案:

答案 0 :(得分:1)

尝试此代码,我只是不知道中断是否是正确的语法,但我保证这是正确的代码

`Dim x As String     选择Case lbl1.Text         情况1             x =" column1"

    Case 2
        x = " column2"

    Case 3
        x = " column3"

    Case 4
        x = " column4"

End Select
        DGV1.Columns.Clear()
        Dim dt As New DataTable
        dt.Clear()
        DGV1.Visible = True
        Dim comm2 As New SqlCommand
        comm2.CommandText = Nothing
        DGV1.Refresh()
        comm2.CommandText = "select first_name,last_name,age from students where " + x + "=" + "yes" + ""
        comm2.Connection = sqlconn
        sqlconn.Open()
        dr2 = comm2.ExecuteReader
        dt.Load(dr2)
        DGV1.AutoGenerateColumns = True
        DGV1.DataSource = dt
        DGV1.Refresh()
        sqlconn.Close()
        DGV1.Visible = True
        comm2.Dispose()`