[英]How to get data from database to textbox on VB.net
您好,我在Visual Basic中是新的。 我有一個按鈕,單擊該按鈕時,它將通過用戶輸入的ID查找學生,並將數據輸出到文本字段。 我不確定我是否做對了。 因為我遇到此錯誤[image] >> http://img812.imageshack.us/img812/7650/gq0z.png
順便說一下,這是到目前為止的代碼。 有人能幫助我嗎? 謝謝!
cmd.CommandText = "Select * from Student where Student_id = '" & id.Text & "'"
cmd.Connection = db
dr = cmd.ExecuteReader
Try
dr.Read()
id.Text = dr.GetValue(0)
Lname.Text = dr.GetValue(1)
Fname.Text = dr.GetValue(2)
Mname.Text = dr.GetValue(3)
datet.Text = dr.GetValue(4)
age.Text = dr.GetValue(5)
male.Text = dr.GetValue(6)
female.Text = dr.GetValue(7)
status.Text = dr.GetValue(8)
staddress.Text = dr.GetValue(9)
cityAdd.Text = dr.GetValue(10)
dr.Close()
Catch ex As Exception
MsgBox("" + ex.Message)
dr.Close()
End Try
cmd.CommandText = "Select * from Student where Student_id = '" & id.Text & "'"
改成:
if IsNumeric(id.text) Then
cmd.CommandText = "Select * from student where Student_id=@p1"
cmd.Prepare
cmd.Parameters.AddWithValue("@p1", id.text)
dr = cmd.ExecuteReader
....
Else
Exit Sub
End If
您可以通過這種方式進行,或者
dr = cmd.ExecuteReader
Try
with dr
.Read()
id.Text = .GetValue(0)
end with
dr.Close()
要么
with dr
.read
id.text = .item("id")
.close
更容易閱讀...
首先添加一個引用,如果您使用的是MySQL數據庫,請下注。 班級
Dim Connection As MySqlConnection
Dim command As MySqlCommand
將此放入您的文本框
Connection = New MySqlConnection
Connection.ConnectionString = "Server=localhost;port=3306;userid=root;password=root;database=databasename"
Dim reader As MySqlDataReader
根是默認的
Try
Connection.Open()
Dim query As String
query= "Select * from Databasename.tablename where fieldname='" & textbox1.text & "'"
Command = New MySqlCommand(query, Connection)
reader = Command.ExecuteReader
While reader.Read
Dim sname As String
sname = reader.GetString("Fieldname")
textbox1.Items.Add(sname)
End While
Connection.Close()
Catch e MySqlException
MsgBox (ex.Message)
Finally
Connection.Dispose
End Try
如果使用的是Mysql數據庫,請首先添加參考。 添加MySql數據庫的引用
查找添加->引用
將會打開一個窗口
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.