I am new to Vb.net and Sql Server(don't be harsh). Can anybody check my code, i feel it is wrong way to do. The purpose is to show query only if check-box is clicked and shows that query. Thank you very much.
Private Sub btnFilter_Click(sender As Object, e As EventArgs) Handles btnFilter.Click
CheckValue = 0 'set to value 0
'check if any checkbox is checked.
For Each C As Control In Me.Controls
If C.GetType Is GetType(CheckBox) Then
Dim cb As CheckBox = DirectCast(C, CheckBox)
If cb.Checked Then
CheckValue = CheckValue + 1 'only works if value is above 1
End If
End If
Next
If CheckValue <> 0 Then 'only if check box is checked then rest will run
Try
If chkboxId.Checked = True Then 'assign value to checkbox
chkboxIdstr = "userid"
Else
chkboxIdstr = ""
End If
If chkboxName.Checked = True Then
chkboxNamestr = "username"
Else
chkboxNamestr = ""
End If
'to insert comma, only if both are true.
If chkboxId.Checked = True And chkboxName.Checked = True Then
SQLcomma = " , "
Else
SQLcomma = ""
End If
'so if both are checked we get a comma
SQL2 = chkboxIdstr + " " + SQLcomma + " " + chkboxNamestr
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try 'sql connect and display
sqlCon.Open()
SQL = "SELECT " + SQL2 + " FROM user_info"
Dim dadapter As New SqlDataAdapter(SQL, sqlCon)
Dim dset As New DataSet
sqlCon.Close()
dadapter.Fill(dset)
'fill datagrid
dgv.DataSource = dset.Tables(0)
Catch ex As Exception
MsgBox(ex.Message)
sqlCon.Close()
End Try
Else
MsgBox("Plesase do check any box to filter ")
Exit Sub
End If
End Sub
-- I learn by doing small application(trail and error), mostly google search for solutions.