检查sql中列的值

时间:2014-04-28 12:43:08

标签: sql vb.net visual-studio-2012 sql-server-2012-express

我正在尝试从数据库中收集值,如果它们是X值,则将背景颜色设置为绿色。

基本上,我有一个Rota系统,如果用户正在工作,那么改变背景颜色。 select *只会带回1行。

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

结束班

在此之后,我理解我需要获得一些IF语句,但我不确定如何构建它们。

1 个答案:

答案 0 :(得分:0)

要检查DataSet使用中的值,请首先获取DataTable,然后选择DataRow,然后选中其中一个字段值:

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

所以要根据某些值改变颜色:

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

其他一些评论:

  • DataSet对于获取一个值可能有点重(除非您重新绑定到控件)。您可以使用ADO.NET对象并使用ExecuteScalar
  • 使用参数而不是连接SQL语句更安全(防止SQL注入和特殊字符的错误)
  • 您可以重构代码,将连接字符串放在一个位置,而不是跨方法复制它。