Question

I am trying to collect values from a database, and if they are X value sett he background colour to green.

Basically, I have a Rota system, and if the user is working, then change the background colour. The select * will only bring back 1 row ever.

Imports System.Data.SqlClient
 Imports System.Data.OleDb

Public Class Form4
Dim Con As SqlConnection
Dim cmd As New OleDbCommand
Dim sqlstring As String
Dim connstring As String
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form4_Load(sender As Object, e As EventArgs)
    connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
    Con = New SqlConnection(connstring)
    Con.Open()
    Dim strSQL As String = "SELECT * from Users"
    Dim da As New SqlDataAdapter(strSQL, Con)
    Dim ds As New DataSet
    da.Fill(ds, "Users")
    With cboname
        .DataSource = ds.Tables("Users")
        .DisplayMember = "Name"
        .ValueMember = "Id"
        .SelectedIndex = 0
    End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Con As SqlConnection
    Dim cmd As New OleDbCommand
    Dim sqlstring As String
    Dim connstring As String
    Dim ds As DataSet
    Dim da As SqlDataAdapter



    connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"

    Con = New SqlConnection(connstring)
    Con.Open()


    sqlstring = ("SELECT * FROM Rota WHERE UserId ='" & cboname.SelectedIndex & "' and ID ='" & dtp1.Value & "'")
    da = New SqlDataAdapter(sqlstring, Con)
    ds = New DataSet
    da.Fill(ds, "Rota")



End Sub

End Class

After this, I understand I need to get a few IF statements, but I am unsure on how to construct them.

Was it helpful?

Solution

To check a value in a DataSet use first get a DataTable inside of it, then a DataRow, then check one of the field values:

 ds.Tables(0).Rows(0)("{field name}");

So to change the color based on some value:

 If ds.Tables(0).Rows(0)("{field name}") = "Red" Then
     textbox1.BackColor = Color.Red
 End If

Some other comments:

  • A DataSet may be a bit heavy for getting one value (unless you're binding to a control). You can just use ADO.NET objects and use ExecuteScalar)
  • It's safer to use parameters instead of concatenating SQL statements (prevents SQL Injection and errors from special characters)
  • You can refactor your code to put the connection string in a single location rather than duplicating it across methods.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top