2013-10-28 43 views
0

嗨im新的Visual Basic。我有一個按鈕,當它被點擊時,它會通過用戶輸入的ID找到學生,並將數據輸出到文本框。我不確定我是否正確地做這件事。因爲我得到這個錯誤[圖像] >>http://img812.imageshack.us/img812/7650/gq0z.png如何從數據庫獲取數據到VB.net上的文本框

btw這是我的代碼到目前爲止。有人能幫助我嗎?謝謝!

 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 
+0

'是空的,你會得到一個錯誤;在構建SQL之前,您還需要將其包含的**文本**轉換爲數字。在未來發布實際的錯誤消息(他們是重要的信息),而不是一個圖片的鏈接 – Plutonix

+0

我會推薦一個:'如果不是isdbnull(dr.getvalue(0))'...每一個明顯增加getvalue每個人的號碼。 – logixologist

+0

未經請求的建議:繼續並將'dr.getvalue(n)'改爲'dr.getvalue(「nameOfColumn」)'。它是一個更好的習慣。 – logixologist

回答

3
cmd.CommandText = "Select * from Student where Student_id = '" & id.Text & "'" 

變化:

if IsNumeric(id.text) Then 
cmd.CommandText = "Select * from student where [email protected]" 
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 

容易ŧ Ø閱讀....

+0

謝謝!我要檢查一下 – phenomenon09

1

首先添加一個引用,如果你使用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 
0

如果你正在使用MySQL數據庫,首先添加引用。要添加MySQL數據庫的參考

  1. 轉到您的解決方案資源管理器中右擊,並在您的項目名稱
  2. 查找添加 - >引用

    窗口將被打開

  3. 在該窗口中,在Assemblies選擇框架下。
  4. 在右側會出現一個列表中找到並選擇Microsoft.VisualBasic.Compatability.Data
  5. 在擴展,發現如果`id.Text添加MySql.Data和MSDATASRC
  6. 單擊確定
相關問題