如何从vb.net中的数据库中显示味精中的值

时间:2018-07-04 06:26:10

标签: sql vb.net

如何在vb.net的数据库中的消息框中显示值?我需要帮助

如果我在文本框中输入错误的值,我想显示值,然后消息框显示数据库中的原始值。

        Dim cmdAB As String
        Dim daAB As SqlClient.SqlDataAdapter
        Dim dsAB As DataSet
        Dim dtAB As DataTable

        cmdAB = "SELECT * FROM English_Test WHERE school_code= '" & school_code & "' and child_id= '" & child_id & "' and english_1= '" & English_1TextBox.Text & "'"
        daAB = New SqlClient.SqlDataAdapter(cmdAB, cnn)
        dtAB = New DataTable()

        dsAB = New DataSet()

        daAB.Fill(dsAB, "English_Test")

        dtAB = dsAB.Tables("English_Test")

        If (dtAB.Rows.Count > 0) Then

            English_2TextBox.Focus()

        Else

            MessageBox.Show("English 1: " & dtAB.Rows(0).Item("english_1") & " not found.", "" & Name & " - Not Found", MessageBoxButtons.OK, MessageBoxIcon.Warning)

            English_1TextBox.Enabled = True
            English_1TextBox.Text = Nothing
            English_1TextBox.Focus()

        End If

1 个答案:

答案 0 :(得分:0)

这种使用参数的方式,以及Using ... EndUsing块,可确保即使有错误,也可以关闭并正确放置对象。

Private Sub CheckOriginalData()
        Dim Name As String = ""
        Dim school_code As String = ""
        Dim child_id As String = ""
        Dim dtAB As New DataTable
        Using cn As New SqlConnection("Your connection string")
            Dim cmdAB As String = "SELECT * FROM English_Test WHERE school_code= @SchoolCode and child_id= @ChildID and english_1= @English1;"
            Using cmd As New SqlCommand(cmdAB, cn)
                cmd.Parameters.Add("@SchoolCode", SqlDbType.VarChar).Value = school_code
                cmd.Parameters.Add("@ChildID", SqlDbType.VarChar).Value = child_id
                cmd.Parameters.Add("@English1", SqlDbType.VarChar).Value = English_1TextBox.Text
                cn.Open()
                Using dr As SqlDataReader = cmd.ExecuteReader
                    dtAB.Load(dr)
                End Using
            End Using
        End Using
        If (dtAB.Rows.Count > 0) Then
            English_2TextBox.Focus()
        Else
            MessageBox.Show("English 1: " & English_1TextBox.Text & " not found.", Name & " - Not Found", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            English_1TextBox.Enabled = True
            English_1TextBox.Text = Nothing
            English_1TextBox.Focus()
        End If
    End Sub

最后,您的问题。如果您的数据表没有行,那么引用行和列以获取值将无法解决。您提供了该值,但它仍在文本框中而不在数据库中。记住,没有找到。