how use datareader while getting a value to the textbox
Hey Friend i am using a form with a *combobox*in which the items i have taken from the sqldatabase named as balance and that s开发者_StackOverflow中文版qldatabase have two columns one is customername and the another is obbalance now .
In the form i had binded all the customer names from the table and now i have a textbox i want to do is when the user selects the combobox.selected item any one customer name i need to display the obbalance of the selected customer in tat textbox
Ihad used the datareader but it shows error can you plz help me........
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 understand how to read plz help me to read the data and in the table first is column name and next is obbalance field
Since you are going read a single value from the database, use ExecuteScalar method instead of using a 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
Update:
Modified the code to check for null.
Removed the datareader object as it is no longer required.
Removed unnecessary characters from query.
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
精彩评论