Imports System.Data.SqlClient
Public Class Form3
Private cs As New SqlConnection("Data Source=HUSAIN-PC;Initial
Catalog=final1;Integrated Security=True”)
Private da As New SqlDataAdapter
Private ds As New DataSet
Public dr As SqlDataReader
Public cmd As New SqlCommand
Private sql As String
Private sqlsel As String
Dim Bal As String
Dim id As String
Dim amt As String
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
cs.Open()
cmd.Connection = cs
amt = TextBox2.Text
id = TextBox1.Text
sqlsel = "SELECT (Bal) FROM db5 WHERE Id='" + id + "'"
da.InsertCommand = New SqlCommand(sqlsel, cs)
dr = cmd.ExecuteReader
If dr.HasRows = True Then
While (dr.Read())
Bal = dr("Id")
End While
End If
dr.Close()
MessageBox.Show("Balance is :" + Bal)
Dim total As String = Bal + amt
sql = "UPDATE db5 SET Bal='" + total + "' WHERE Id='" + id + "'"
da.InsertCommand = New SqlCommand(sql, cs)
da.InsertCommand.ExecuteNonQuery()
MessageBox.Show("updated")
End Sub
End Class
This is my VB code to retrieve a value from the SQL DB…the Update statement is running fine bt wen i write the select i get an exception in the code:
dr=cmd.ExecuteReader
“ExecuteReader: CommandText property has not been initialized”
Look at this code:
You’re specifying an
InsertCommandas a SELECT query, but then you’re callingExecuteReaderon a completely separateSqlDataReader… which hasn’t got a query configured, as per the error message.That’s why you’re getting this specific error, but there are lots of problems with this code:
SqlConnection/SqlCommandetc every time you want to execute a queryUsingstatements to automatically close themDataAdapterhere in the first place – just useSqlCommand.ExecuteNonQuery