I'm getting this error "InvalidOperationException was Unhandled" [duplicate] - vb.net

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.

Related

.executenonquery() error No value given for one or more required parameters

Imports System.Data.OleDb
Public Class LoginForm
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\thesis\YBIM.accdb"
Dim conn As New OleDbConnection
' TODO: Insert code to perform custom authentication using the provided username and password
' (See http://go.microsoft.com/fwlink/?LinkId=35339).
' The custom principal can then be attached to the current thread's principal as follows:
' My.User.CurrentPrincipal = CustomPrincipal
' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
' such as the username, display name, etc.
Private Sub LoginForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn.ConnectionString = connstring
If conn.State = ConnectionState.Closed Then
conn.Open()
MsgBox("welcome")
Else
MsgBox("Cannot connect to database")
End If
End Sub
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim SqlQuery As String = ("SELECT * FROM tablelogin WHERE Username= #field1 AND Password=#field2")
Dim SqlCommand As New OleDbCommand
Dim Sqlrdr As OleDbDataReader
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.Parameters.AddWithValue("#field1", UsernameTextBox.Text)
.Parameters.AddWithValue("#field2", PasswordTextBox.Text)
.ExecuteNonQuery()
End With
Sqlrdr = SqlCommand.ExecuteReader()
If (Sqlrdr.Read() = True) Then
home.ShowDialog()
Me.Hide()
Else
MsgBox("wong input")
End If
End Sub
End Class
There are two things of note in your code which you can remedy.
1* You are naming your parameters incorrectly.
This:
.Parameters.AddWithValue("#field1", UsernameTextBox.Text)
.Parameters.AddWithValue("#field2", PasswordTextBox.Text)
Should be this:
.Parameters.AddWithValue("field1", UsernameTextBox.Text)
.Parameters.AddWithValue("field2", PasswordTextBox.Text)
2* You are executing the command twice. Remove .ExecuteNonQuery() from the With statement,
and change:
Sqlrdr = SqlCommand.ExecuteReader()
to
Dim ret As Integer
ret = SqlCommand.ExecuteNonQuery()
And instead of using Sqlrdr.Read(), simply check if ret > 0 (ExecuteNonQuery returns the amount of rows affected by the command).

Listbox Database

Okay, so for a project I'm not allowed to use Datagridview and instead I'll have to use a Listbox to display data from a database when it is searched for. I'll link my code below, could anyone please tell me how I can change this code to suit a listbox. I'm a noob to programming so if I've made any obvious mistakes please forgive me
Imports System.Data
Imports System.Data.OleDb
Public Class frmUserList
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub Load_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
'try catch block is used to catch the error
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT user_id, last_name + ', ' + first_name + ' ' + mid_name as name FROM users where last_name + ', ' + first_name + ' ' + mid_name like '%" & Me.txtSearch.Text & "%' or [first_name] = '" & Me.txtSearch.Text & "'"
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Load_Record()
End Sub
Private Sub dtgResult_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtgResult.DoubleClick
If Me.dtgResult.SelectedRows.Count > 0 Then
Dim frm As New frmMarkSeat
frm.txtFname.Tag = Me.dtgResult.Item(0, Me.dtgResult.CurrentRow.Index).Value
frm.ShowDialog()
frm = Nothing
End If
End Sub
End Class
Give this a try using SQLDataReader: (untested code, just wrote out of hand).
'start here
conn.Connection.Open()
Dim sqlDR As SqlDataReader
Dim colValue As String
sqlDR = conn.ExecuteReader
While sqlDR.Read
colValue = (sqlDR.GetValue(0)).ToString
ItemlistBox.Items.Add(colValue)
ItemlistBox.Sorted = True
End While
conn.Connection.Close()
Or you can keep using your current objects, with additional object DataSet and populate the listbox.
Dim dtset As New DataSet
Dim da As New OleDbDataAdapter
da.Fill(dtset)
ItemListBox.DataSource = dtset
ItemListBox.DisplayMember = "ColName"

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.

Error in Code - dbCommand.ExecuteReader()

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