这是我的数据库表
1 abc
2 xyz
它输入1然后各自的值“abc”显示在不同的文本框???
Private Sub butsea_Click(sender As Object, e As EventArgs) Handles butsea.Click
Dim dset As New DataSet
Dim da As SqlDataAdapter
Dim myCmd As New SqlCommand
Try
myConn.ConnectionString = "Data Source=THEONE\PARTH;Initial Catalog=testdatabase;Integrated Security=True;"
myConn.Open()
Dim avalue As String = (InputBox("Input Student Id", "Search Student")).ToString
txt_id.Text = avalue
da = New SqlDataAdapter("SELECT * FROM studentdetails where student_id= '" & txt_id.Text & "", myConn)
If dset.Tables(0).Rows.Count > 0 Then
'what should i write here
Else
MsgBox("No Record Found")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
End Sub
答案 0 :(得分:2)
如果你只需要获取一个值 - 使用DataAdapter和DataSet是过度的。使用SqlCommand.ExecuteScalar
方法并在查询中代替“SELECT * ...”执行“SELECT YOURFIELD ...”。
这样你就不必跳过建立数据集的箍,检查行数等,而只是检查Nothing的返回值。
更新 以下是您修改为使用ExecuteScalar的代码
Private Sub butsea_Click(sender As Object, e As EventArgs) Handles butsea.Click
Dim myCmd As SqlCommand
Dim myConn As New SqlConnection
Dim oResult As Object
Try
myConn.ConnectionString = "Data Source=THEONE\PARTH;Initial Catalog=testdatabase;Integrated Security=True;"
myConn.Open()
Dim avalue As String = (InputBox("Input Student Id", "Search Student")).ToString
txt_id.Text = avalue
myCmd = New SqlCommand("SELECT student_name FROM studentdetails where student_id= '" & txt_id.Text & "'", myConn)
oResult = myCmd.ExecuteScalar()
If oResult IsNot Nothing Then
txt_name.text = oResult.ToString
Else
MsgBox("No Record Found")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
End Sub
此代码假定您需要显示的数据库字段名为student_name
,并且您将名为txt_name
的TextBox添加到表单中。
答案 1 :(得分:1)
您需要为要显示的每个字段添加其他文本框
(例如,名为txtStudentName的文本框可用于名称,依此类推,用于表studentdetails
中的其他字段。)
查询数据库的正确方法(省略其他方法,如使用SqlDataReader)应该是以下
Dim dset As New DataSet
Dim da As SqlDataAdapter
Try
myConn.ConnectionString = "Data Source=THEONE\PARTH;Initial Catalog=testdatabase;Integrated Security=True;"
myConn.Open()
Dim avalue As String = (InputBox("Input Student Id", "Search Student")).ToString
txt_id.Text = avalue
' prepare the adapter with a commandtext. Do not use string concatenation from user input'
da = New SqlDataAdapter("SELECT * FROM studentdetails where student_id=@id", myConn)
da.SelectCommand.Parameters.AddWithValue("@id", txt_id.Text)
' Fill the dataset'
da.Fill(dset)
If dset.Tables(0).Rows.Count > 0 Then
' Supposing you have a field for the studentname in the first column of the returned
' datatable rows(rowindex)(columnindex)
txtStudentName.Txt = dset.Tables(0).Rows(0)(0).ToString()
.....
' Set the text property of other textboxes for other fields to show'
Else
MsgBox("No Record Found")
End If