mohamed soliman mohamed soliman - 5 months ago 7
Vb.net Question

use select case condition with SQL query statement in vb.net

I try to use select case statement with SQL statement
I have 4 columns when the lbl1.text equal 1 then x = "column1" and put this value in the SQL statement
when I try this code

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


and when lbl1.text = 1 or 2 or 3 it doesn't run the SQL statement but when the lbl1.text = 4 it's run SQL statement
can any one help me in this code

Answer

try this code, i just don't know if the break is the right syntax, but i guarantee you that this is the right code

Dim x As String Select Case lbl1.Text Case 1 x = "column1" break; Case 2 x = " column2" break; Case 3 x = " column3" break; Case 4 x = " column4" break; 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()

Comments