[英]how to get data from database and put it on the textbox - vb.net
你好,我试图从数据库中获取数据,当我在comboxbox上单击“ 720”时,他将在数据库中获取“ pp12”列的数据并将其放入文本框,而当我在数据库上单击“ 1440”时, combobox它将从数据库的“ 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
您没有说什么是行不通的。
您的代码可以进行一些重构,以避免两次编写相同的代码。 同样,您不应该挂起连接:打开连接,执行查询,关闭连接。 最终,您的代码将仅显示结果集中的最后一个结果。 我假设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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.