Textbox 配合 SQL Query + SqlDataReader + Textbox 使用方法

 
Textbox 配合 SQL Query + SqlDataReader + Textbox 使用方法
 

   Form1.vb
 
   Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As KeyEventArgs) _
   Handles TextBox1.KeyUp
 
      If e.KeyCode = Keys.Enter Then
 
         Dim A As String
 
         Try
            A = CStr(CInt(TextBox1.Text.Trim()))
         Catch ex As Exception
            A = "0"
         End Try
 
         getdataTB(A)
 
      End If
 
   End Sub
 
   Private Sub getdataTB(ByVal A As String)
 
      Try
 
         If Not (A = 0) Then
 
            Dim connectionString1 As String = "Data Source=.\SqlExpress; Initial Catalog=Soccer; Integrated Security=SSPI"
            Dim con1 As SqlConnection = New SqlConnection(connectionString1)
            con1.Open()
 
            Dim SqlString1 As String = "SELECT Player_ID, Player_Name FROM dbo.Player WHERE Player_ID = '" & A & "'"
 
            Dim cmd1 As SqlCommand = New SqlCommand(SqlString1, con1)
 
            Dim dr As SqlDataReader = cmd1.ExecuteReader()
 
            If dr.HasRows Then
 
               Do While dr.Read
 
                  TextBox2.ReadOnly = False
                  TextBox2.Text = dr.Item("Player_ID").ToString().Trim
 
                  TextBox3.ReadOnly = False
                  TextBox3.Text = dr.Item("Player_Name").ToString().Trim
 
               Loop
 
            Else
 
               TextBox2.ReadOnly = True
               TextBox2.Text = ""
 
               TextBox3.ReadOnly = True
               TextBox3.Text = ""
 
            End If
 
            cmd1.Dispose()
            con1.Dispose()
 
         Else
 
            TextBox2.ReadOnly = True
            TextBox2.Text = ""
 
            TextBox3.ReadOnly = True
            TextBox3.Text = ""
 
         End If
 
      Catch ex As Exception
 
      End Try
 
   End Sub