2013-07-29 36 views
-2

我正在做一個VB.NET項目。我有一個表單,其中有3個文本框和一個命令按鈕。如何從Microsoft SQL Server 2008表中檢索值到Windows窗體TextBox的值:

當我向TextBox1(它是患者的註冊號碼)輸入一個值並點擊命令按鈕(SearchButton)時,它必須從我的SQL Server表中搜索值並在TextBox2和TextBox3中給出結果(這是患者的姓名和年齡)。

這是我做的,但它不工作。

Dim cn As New SqlConnection 
    cn.ConnectionString = "Data source=localhost\SQLEXPRESS;Initial Catalog=hms;Integrated Security=True" 
    cn.Open() 
    Dim cm As New SqlCommand 
    cm.CommandText = "SELECT Patient_Name,Age FROM Patient_Prescrib" 
    cm.Connection = cn 
    Dim dr As SqlDataReader 
    dr = cm.ExecuteReader 

    If dr.HasRows Then 

     dr.Read() 
     ' TextBox1.Text = dr.Item("Reg_No") 
     TextBox3.Text = dr.Item("Patient_Name") 
     TextBox4.Text = dr.Item("Age") 
     dr.Close() 

    End If 
    cn.Close() 
+1

**(1)**完全重複【如何從SQL Server檢索表值文本框(http://stackoverflow.com/questions/17933651/how-to-retrieve-values - 從-SQL服務器表到文本框)。 **(2)**這是在*清理完第一個問題之後發佈的,並且您還沒有解釋**有什麼問題**。如果您沒有立即得到回覆,請不要提出新問題,否則這隻會使網站混亂,並會刺激用戶。 **(3)**這是VB.NET,而不是VB6,請停止使用[vb6]標籤。 [微軟]標籤也不需要。 – LittleBobbyTables

+0

我認爲你需要SQL上的WHERE子句來將返回的數據縮小到單個記錄。 WHERE Pat_ID = 123456例如 – rheitzman

+0

看起來您需要將where子句添加到您的sql語句中,以便您可以搜索輸入病人的註冊號碼。否則,您沒有任何標準可以讓您知道患者是從數據庫中帶回來的。你得到的錯誤是什麼? – SoftwareCarpenter

回答

0

@SoftwareCarpenter,@ D_Bester,@rheitzman謝謝You.This是我做的,並得到它的權利。 :)

Private Sub DetailsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DetailsButton.Click 
    Try 
     Dim con As SqlConnection = New SqlConnection 
     con.ConnectionString = "Data source=localhost\SQLEXPRESS;Initial Catalog=hms;Integrated Security=True" 
     con.Open() 
     Dim dt As New DataTable 
     Dim ds As New DataSet 
     ds.Tables.Add(dt) 
     Dim da As New SqlDataAdapter 
     da = New SqlDataAdapter("SELECT * from Patient_Prescrib WHERE Reg_No LIKE '%" & TextBox1.Text & "%'", con) 
     da.Fill(dt) 
     For Each DataRow In dt.Rows 
      If TextBox1.Text = dt.Rows(0)("Reg_No").ToString Then 

       TextBox2.Text = dt.Rows(0)("Patient_Name").ToString 
       TextBox3.Text = dt.Rows(0)("Patient_Con").ToString 

       MessageBox.Show("Patient details added!") 
       Return 
      End If 
     Next 
     con.Open() 
     Return 
     con.Close() 
    Catch ex As Exception 
     MessageBox.Show(" a run time error has occured. Please make sure you have provided the reg no for search") 

    End Try 

End Sub