如何从数据库中获取数据并将其放在文本框中--vb.net

时间:2014-03-16 20:06:06

标签: vb.net

你好,当我点击我的comboxbox上的“720”时,我试图从数据库中获取数据,他将从我的数据库中获取数据形式“pp12”列并将数据放入文本框,当我点击“1440”时“在组合框上,它将从DB中的”pp24“列获取数据并将数据放入文本框中,我的代码谢谢你们。

代码:

   Private Sub cmbnot_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbnot.SelectedIndexChanged

    Dim nsi As String = txtchange.Text

    Select Case nsi

        Case "720"

            With cmd
                .Connection = conn
                .CommandText = "select * from tblCycle"
            End With

            dr = cmd.ExecuteReader

            If dr.HasRows Then
                While dr.Read
                    txtpd.Text = dr.Item("pp12")
                End While
                dr.Close()
            End If

        Case "1440"

            With cmd
                .Connection = conn
                .CommandText = "Select * from tblCycle"
            End With

            dr = cmd.ExecuteReader

            If dr.HasRows Then

                While dr.Read
                    txtpd.Text = dr.Item("pp24")
                End While
                dr.Close()
            End If
    End Select

1 个答案:

答案 0 :(得分:0)

你没有说什么不起作用。

您的代码可以通过一些重构来避免两次编写相同的代码。此外,您不应该有连接:打开连接,执行查询,关闭连接。您的代码最终只显示结果集中的最后一个结果;我假设txtpd设置为多行。

Option Strict On

Imports System.Data.SqlClient
Imports System.Text


Private Sub cmbnot_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbnot.SelectedIndexChanged
     ' should the following be CStr(cmbnot.SelectedItem) ?
     Dim nsi As String = txtchange.Text

     ' We are going to select only the column which is actually needed.
     Dim dbColumn As String = ""

     Select Case nsi
         Case "720"
             dbColumn = "[pp12]"
         Case "1440"
             dbColumn = "[pp24]"
     End Select

     If dbColumn <> "" Then

         Dim sql As String = String.Format("SELECT {0} FROM [tblCycle]", dbColumn)
         Dim result As New StringBuilder

         ' The "Using" construct takes care of calling .Dispose() for you.
         Using conn As New SqlConnection("YOUR CONNECTION STRING")
             Using cmd As New SqlCommand(sql, conn)
                 conn.Open()
                 Dim dr As SqlDataReader = cmd.ExecuteReader()
                 If dr.HasRows() Then
                     While dr.Read()
                         result.AppendLine(dr.GetString(0))
                     End While
                 End If
                 conn.Close()
             End Using
         End Using

         txtpd.Text = result.ToString()

     End If

 End Sub