[英]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.