Error in Code - dbCommand.ExecuteReader() - vb.net

Can anyone tell me How do I solve this error.
Error: NullReferenceException was Unhandled - "Object reference not set to an instance of an object."
Line: Dim reader As OleDbDataReader = dbCommand.ExecuteReader()
Database: MS Access
IDE: VB 2010 Express
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System
Public Class Form1
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim strInsert As String
Dim dbDataAdapter As OleDbDataAdapter
Dim ConnectString As String = "Provider = Microsoft.Jet.OLEDB.4.0;" & "Data Source =atg.mdb"
Private Sub Form1_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
dbConnection = New OleDbConnection(ConnectString) 'here I use the new keyword to initialize connection
dbConnection.Open()
Dim command As New OleDbCommand("SELECT XX FROM ABC", dbConnection) ' initialize command and pass query and open connection to its constructor
Dim reader As OleDbDataReader = dbCommand.ExecuteReader() 'ERROR IS HERE
Do While (reader.Read()) ' loop here until reader finish reading and add every row to the list box
ListBox1.BeginUpdate()
ListBox1.Items.Add(reader.Item("ABC"))
ListBox1.EndUpdate()
Loop
reader.Close()
dbConnection.Close()
End Sub
End Class

Where you find dbCommand in dbCommand.ExecuteReader() statement.Use command.ExecuteReader() instead .
You didn't initiate your dbCommand.You just Decalared it.What you did is creating another variable called command and initiated it.So try with this

Part of the programma:
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'MajDgv()
Module1.connect()
Me.fillcombo()
End Sub
Sub fillcombo()
strsql = "select from Liste des responsables"
Dim acscmd As New OleDb.OleDbCommand
Dim acsdr As OleDbDataReader
acscmd.CommandText = strsql
acsdr = acscmd.ExecuteReader()""THE PROBLEM IS HERRE he sayed that ExecuteReader: Connection property has not been initialized."""""""
While (acsdr.Read())
ComboBox1.Items.Add(acsdr("Nom"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
End Class
I create a Module:
Imports System.Data.OleDb
Module Module1
Public acsconn As New OleDb.OleDbConnection
Public acsdr As OleDbDataReader
Public strsql As String
Sub connect()
acsconn.ConnectionString = "Provider=Microsoft.ace.oledb.12.0;data source=|datadirectory|\Base1.accdb;"
acsconn.Open()
End Sub
End Module

Related

I'm getting this error "InvalidOperationException was Unhandled" [duplicate]

I'm getting this error: "ErrorExecuteReader: Connection property has not been initialized"
I can't figure out what the problem is.
Imports System.Boolean
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_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
Dim userID As String
Dim password As String
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim reader As SqlDataReader
userID = txtuser.Text
password = txtpassword.Text
txtuser.Text = Focus()
txtpassword.Visible = "False"
Try
conn = New SqlConnection("Data Source=XXXXXX;Initial Catalog=XXXXXXUser ID=XXXXXX;Password=XXXXXX")
cmd = New SqlCommand("Select user,password from userlog where user='" + userID + "' & password='" + password + "'")
conn.Open()
reader = cmd.ExecuteReader()
conn.Close()
If (String.Compare(password, 123) = 0) Then
MsgBox("Success")
End If
Catch ex As Exception
MsgBox("Error" + ex.Message())
End Try
End Sub
End Class
The connection property of your command object hasn't been set. Add it to your constructor like so:
cmd = New SqlCommand("...", conn)
Or set the Connection property like so:
cmd.Connection = conn
By the way, this error should have been easy to catch if you were debugging in Visual Studio.

GETTING ERROR when updating database in vb.NeT

I'M Creating A Database updater using vb.NET and database AS DATABASE1.SDF. I I WANTED TO Update the DATABASE IN DATAGridview dynamically. For UPDATING SQL COMMAND i'm USING A SQLCECOMMANDBUILDER BUT I'M GETTING A ERROR THERE AS "The DataAdapter.SelectCommand property needs to be initialized."
HERE IS MY CODE:
Imports System.Data.OleDb
Imports System.Data
Imports System.Data.SqlServerCe
Public Class Admin
Dim update As New SqlCeDataAdapter
' sql connection strings
Dim SQLCon As String = "Data Source=Database1.sdf"
Dim sqlstr As String = "Select * from Base_Plate "
Dim sqlstr1 As String = "Select * from Alloy "
Dim sqlstr2 As String = "Select * from Bead_Factor "
Dim sqlstr3 As String = "Select * from Difficulty_Factor "
Dim sqlstr4 As String = "Select * from Price_Factor "
' sql variable of base
Dim adapter As New SqlCeDataAdapter(sqlstr, SQLCon)
Dim ds As New DataSet()
' sql variable of alloy
Dim adapter1 As New SqlCeDataAdapter(sqlstr1, SQLCon)
Dim ds1 As New DataSet()
' sql variable of bead
Dim adapter2 As New SqlCeDataAdapter(sqlstr2, SQLCon)
Dim ds2 As New DataSet()
'sql variable of difficulty
Dim adapter3 As New SqlCeDataAdapter(sqlstr3, SQLCon)
Dim ds3 As New DataSet()
'sql variable of price
Dim adapter4 As New SqlCeDataAdapter(sqlstr4, SQLCon)
Dim ds4 As New DataSet()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
update.Update(ds)
LoadGrid()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Visible = False
LoginForm1.Visible = True
End Sub
Private Sub Admin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadGrid()
Button2.Enabled = False
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
End Sub
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
Button2.Enabled = True
End Sub
Private Sub LoadGrid()
'************** base datagrid ********************
adapter.Fill(ds, "Base_Plate")
DataGridView1.DataSource = ds.Tables(0)
DataGridView1.Rows(0).Selected = True
'***************** alloy datagrid *********************
adapter1.Fill(ds1, "Alloy")
DataGridView2.DataSource = ds1.Tables(0)
DataGridView2.Rows(0).Selected = True
'***************** bead datagrid *********************
adapter2.Fill(ds2, "Bead_Factor")
DataGridView3.DataSource = ds2.Tables(0)
DataGridView3.Rows(0).Selected = True
'***************** difficulty datagrid *********************
adapter3.Fill(ds3, "Difficulty_Factor")
DataGridView4.DataSource = ds3.Tables(0)
DataGridView4.Rows(0).Selected = True
'***************** Price datagrid *********************
adapter4.Fill(ds4, "Price_Factor")
DataGridView5.DataSource = ds4.Tables(0)
DataGridView5.Rows(0).Selected = True
update.UpdateCommand = New SqlServerCe.SqlCeCommandBuilder(update).GetUpdateCommand
End Sub
You're doing it wrong. Firstly, as the error message states, you haven't set the SelectCommand of the data adapter that you're passing to the command builder constructor. Here's the relevant snippets from your code:
Dim update As New SqlCeDataAdapter
update.UpdateCommand = New SqlServerCe.SqlCeCommandBuilder(update).GetUpdateCommand
As you can see, nowhere do you provide a SQL SELECT statement so how is the command builder supposed to know how to build the other commands?
Secondly, even if the adapter was properly configured, this is wrong:
update.UpdateCommand = New SqlServerCe.SqlCeCommandBuilder(update).GetUpdateCommand
You DO NOT have to get the commands from the command builder and assign them to the properties of the data adapter. The only reason to do that is if you want to edit them, which you do not. The proper way to create a command builder is on the line immediately after you create the data adapter, e.g.
Dim myDataAdapter As New SqlCeDataAdapter(query, myConnection)
Dim myCommandBuilder As New SqlCeCommandBuilder(myDataAdapter)
That's it. You create it once and once only and then the data adapter will just work when you call Update. There's no creating a new one each time you save and there's no getting and assigning of commands.

How will I print datagridview contents on crystal report in vb.net?

Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.OleDb
Public Class Form2
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim SqlQuery As String = "SELECT * FROM TBLName WHERE ID = " & Form1.Datagridview1.SelectedRows(0).Cells(0).Value.ToString() & ""
Dim SqlCommand As New OleDbCommand
Dim SqlAdepter As New OleDbDataAdapter
Dim Table As New DataTable
With SqlCommand
.CommandText = SqlQuery
.Connection = Form1.conn
End With
With SqlAdepter
.SelectCommand = SqlCommand
.Fill(Table)
End With
Dim crystal As New CrystalReport1
crystal.SetDataSource(Table)
rptviewer.ReportSource = crystal
rptviewer.Refresh()
End Sub
End Class
I'm getting an error on this line
.Connection = Form1.conn
what should I do??

SQL connection error showing INVALID OBJECT NAME

I have done follwing coding but it shows error
Invalid object name 'sanket'
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim da As SqlDataAdapter
Dim ds As New DataSet
Dim str As String
Private Sub ConnectToSQL()
Try
con.ConnectionString = "Data Source=SA_N_KET-PC\SQLEXPRESS;Initial Catalog=repeat;Integrated Security=true;"
con.Open()
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
'DoNothing.
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'CryrptDataSet.sanket' table. You can move, or remove it, as needed.
Me.SanketTableAdapter.Fill(Me.CryrptDataSet.sanket)
ConnectToSQL()
End Sub
Public Sub exe()
str = "insert into sanket(n)values ('" & TextBox1.Text & "')"
da = New SqlDataAdapter(Str, con)
da.Fill(ds, "sanket")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
exe()
End Sub
End Class

I'm trying to create a login form in VB.NET. I'm having some difficulties running my form

I got the error "invalid cast exception unhandled." I'm using SQL Server 2008 and Visual Studio 2008. I get conversion from String "Jack" to type Boolean is not valid.
See the code of my form below:
Imports System.Boolean
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_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
Dim username As String
Dim pswd As String
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim reader As SqlDataReader
username = txt_username.Text
pswd = txt_password.Text
txt_username.Text = Focus()
txt_password.Visible = "False"
Try
conn = New SqlConnection("data source=TAMIZHAN\SQLEXPRESS;persistsecurity info=False;initial catalog=log;User ID=sa;Password=123");
cmd = New SqlCommand("Select usename,passw from Userlog where usename='" + username + "' & passw='" + pswd + "'")
conn.Open()
reader = cmd.ExecuteReader()
If (String.Compare(pswd and '"+passw+"')) Then
MsgBox("Success")
End If
If (reader.Read()) Then
MsgBox("Login success")
End If
conn.Close()
Catch ex As Exception
MsgBox("Error"+ex.Message());
End Try
End Sub
End Class
The string.Compare returns an Integer not a boolean and should be called in this way
If (String.Compare(pswd,passw) = 0) Then
MsgBox("Success")
End If
Please see the references on MSDN
However your code has many problems as it stands now:
You are using string concatenation to build your sql text
(SqlInjection, Quoting problems).
You don't use the Using statement (connection remains open in case of
exception).
The compare logic seems to be absolutely not needed.