[英]Displaying Data from SQL to vb.net textbox
我正在尝试将数据从sql server检索到vb.net文本框,但我不知道该怎么做,我所拥有的所有教程只是将记录从数据库检索到datagrid视图..请帮助。
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
cn.Open()
With cmd
.Connection = cn
.CommandText = "SELECT * FROM Students WHERE RFID like '%" & txtrfid.Text & "%'"
End With
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
cn.Close()
txtname.Text = 'Firstname'
您正在用数据库中的数据填充DataTable
,因此必须将数据从该DataTable
到TextBox
。 您可以通过数据绑定来做到这一点,这就是您可能看到它通过网格完成的方式,例如
txtname.DataBindings.Add("Text", dt, "Firstname")
如果您要检索多个要导航的记录,那肯定是这么做的方法,尽管您可能会在两者之间使用BindingSource
。 如果只有一条记录,那么您可以改为手动移动数据,例如
txtname.Text = CStr(dt.Rows(0)("Firstname"))
如果您只想显示Table中的单个值( FirstName
),请参见以下代码
Using conn As New SqlConnection("connstr")
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim txtName As String
cmd.CommandText = "SELECT firstname FROM Students WHERE RFID ='" & txtrfid.Text & "'"
txtName = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
If txtName <> "" Then
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
Textbox1.Text = ""
Textbox1.Text = txtName
else
MsgBox("No Record Found!", MsgBoxStyle.Information, "INFO.")
End If
End Using
有很多方法可以检索数据。 您可以使用sql数据读取器将数据从sql数据库检索到文本框,这是我的最爱之一。 让我分享给你。 注意:不要忘记导入system.data.sqlclient
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
strConn = "Data Source=" & servernamehere & ";Initial Catalog=" & databasenamehere & ";User ID=" & userid & ";Password=" & password
sqlConn = New SqlConnection(strConn)
sqlConn.Open()
Dim sqlcmd As New SqlCommand("Your query here", sqlConn)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
txtrfid.Text = myreader.Item("column name from sql database table").Tostring
End If
sqlConn.Close()
End Sub
您可以使用尝试捕获技术来捕获异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.