嘿朋友我正在使用带有* 组合框 *的表单,其中我从中获取的项目 sqldatabase命名为balance,sqldatabase有两列,一列是customername和 另一个是现在的不平衡。
在表格中,我已经从表格中绑定了所有客户名称,现在我有一个我想要做的文本框 当用户选择combobox.selected项时,任何一个客户名称我需要在tat文本框中显示所选客户的不平衡
Ihad使用了datareader,但它显示错误,你可以帮助我........
Dim ST As String = ComboBox1.SelectedItem
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
Dim sdr As New SqlDataReader
Try
con.Open()
sdr = sqlcmd.ExecuteReader
While (sdr.Read())
Textbox7.Text = sdr[1]
End While
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
Icant了解如何阅读plz帮我读取数据,表中首先是列名,接下来是obbalance字段
答案 0 :(得分:3)
由于您要从数据库中读取单个值,因此请使用 ExecuteScalar 方法而不是使用datareader。
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = '" & ST & "'" , sqlcon)
Dim result as Object
Try
con.Open()
result = sqlcmd.ExecuteScalar()
If result IsNot Nothing Then
Textbox7.Text = result.ToString()
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
<强>更新强>
修改代码以检查null
删除了不再需要的datareader对象
从查询中删除了不必要的字符。
答案 1 :(得分:0)
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
Dim sdr As SqlDataReader
Try
sqlcon.Open() 'edited
sdr = sqlcmd.ExecuteReader()
While (sdr.Read())
TextBox1.Text = sdr("OBBALANCE").ToString() 'sdr(1) is wrong since there is only one item
End While
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try