hello Im trying to get the data from the database when I click like "720" on my comboxbox he will get thee data form "pp12" column in my database and put the data to a textbox, and when i click "1440" on the combobox it will get the data from "pp24" column in DB and put the data in the textbox heres my code thank you guys.
The code:
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
You didn't say what does not work.
Your code could do with some refactoring to avoid writing the same code twice. Also, you should not have connections hanging around: open the connection, perform the query, close the connection. Your code as it is ends up displaying only the last result from the result set; I have assumed that txtpd
is set to multiline.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.