The connection string property has not been initialized - vb.net

I am trying to search my database using the below code, but I am getting the above error.
Private Sub ButtonSearch_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSearch.Click
myConnection.Open()
Textlocation.Clear()
Dim str As String
str = "select * From STUDENTS where ADMINNO like " & "'%" & SearchTextBox.Text & "%'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
Textadminac.Text = dr("ADMINNO").ToString
End While
myConnection.Close()
End Sub

Related

data type mismatch criteria expression in vb.net,access while inserting

Imports System.Data.OleDb
Imports System.IO
Public Class insuranceform
Dim read As String
Dim datafile As String
Dim connstring As String
Dim cmd As New OleDbCommand
Public da As New OleDbDataAdapter
Dim str As String
Public ds As New DataSet
Public ds1 As New DataSet
Public ds2 As New DataSet
Dim myconnection As OleDbConnection = New OleDbConnection
Dim er As Integer
Private Sub insuranceform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
read = "provider=microsoft.ace.oledb.12.0;data source="
datafile = "C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
connstring = read & datafile
myconnection.ConnectionString = connstring
ds.Clear()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
If myconnection.State = ConnectionState.Open Then
myconnection.Close()
End If
myconnection.Open()
er = 0
'cn.Open()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
ds.Clear()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
If er = 0 Then
Try
cmd.Connection = myconnection
cmd.CommandText = "insert into insurancedetail(Name,EmployeeID,PAN,UniversalAccountNumber,AdharNo,CurrentAddress,PermanentAddress,Landline,MartialStatus,MobileNumber,EmergencyContactNo,BloodGroup,DoyouHaveHDFCbankaccount,NameOfdependentmember_F) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & "','" & ComboBox2.Text & "','" & TextBox9.Text & "','" & TextBox10.Text & "','" & TextBox11.Text & "','" & ComboBox1.Text & "','" & TextBox12.Text & "')"
cmd.ExecuteNonQuery() 'if command is executed'
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
ElseIf result = DialogResult.Yes Then
ds.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
DateTimePicker3.ResetText()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'insert close
End If
'myconnection close
End Sub
Way too many Class level variables. Especially not myconnection and cmd. What in the world is er? Procedures should not do too much. Move some code off to other procedures, especially if they will be called more than once.
For database objects use Using blocks. They will ensure that your objects are closed and disposed even if there is an error. You don't appear to be using the DataAdapter so just fill a DataTable directly. It can be bound to a DataGridView.
There is no reason to fill the DataTable again before the save. You may want to refill is again after the save.
I am guessing at the datatypes in your database. You must check the database to get the correct datatypes and for string types get the size of the field. Convert your TextBox values to the correct types. I have only used a few of your fields for demonstration purposes. Make sure you add your parameters in the same order that they appear in the sql statement.
Private dt As New DataTable
Private connString As String = "provider=microsoft.ace.oledb.12.0;data source=C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetDatePickerValues()
FillDataTable()
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert Into insurancedetail(Name,EmployeeID,PAN) Values(#Name, #EmployeeID, #PAN);", cn)
cmd.Parameters.Add("#Name", OleDbType.VarChar, 100).Value = TextBox1.Text
cmd.Parameters.Add("#EmployeeID", OleDbType.Integer).Value = CInt(TextBox2.Text)
cmd.Parameters.Add("#PAN", OleDbType.VarChar, 100).Value = TextBox3.Text
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
FillDataTable()
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
Else
ClearForm()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ClearForm()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
SetDatePickerValues()
End Sub
Private Sub FillDataTable()
Try
dt.Clear()
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Select * From insurancedetail", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub SetDatePickerValues()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
End Sub

Read data from a database in vb.net

So I used this piece of sample code to retrieve data from a MS Access Database and display it on a few textboxes on the form. The following error occurs -
# dr = cmd.ExecuteReader - Data type mismatch in criteria expression.
dr = cmd.ExecuteReader
This is the sample code -
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\example\Desktop\Data.accdb" ' Change it to your Access Database location
connString = provider & dataFile
myConnection.ConnectionString = connString
End Sub
Dim r As Random = New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Dim str As String
str = "SELECT * FROM Items WHERE (Code = '" & r.Next(1, 3) & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr("Description").ToString
TextBox2.Text = dr("Cost").ToString
TextBox3.Text = dr("Price").ToString
End While
myConnection.Close()
End Sub
Try this ..
str = "SELECT * FROM Items WHERE (Code = '" & (r.Next(1, 3)).ToString() & "')"
try this:
str = "SELECT * FROM Items WHERE (Code = '" & cStr(r.Next(1, 3)) & "')"
The table name in the file that you provided for download is "Table1" not "Items".
Change the query string to:
str = "SELECT * FROM Table1 where (Code = '" & r.Next(1, 3) & "')"

How to get count of records in a table?

Someone help me
I am working on our project and I need to check if my DB has already 20 records.
If so, then it will not accept records anymore.
I've been trying the codes below:
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim ds, ds2 As New DataSet
Dim da, da2 As OleDb.OleDbDataAdapter
Dim sql, sql1 As String
Dim int As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.ConnectionString = "Provider=Microsoft.jet.OLEDB.4.0; data source = |datadirectory|\Database6.mdb"
con.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts WHERE Username='" & TextBox1.Text & "'", con)
Dim sdr As OleDb.OleDbDataReader = cmd.ExecuteReader
Dim cmd1 As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts")
sql = "INSERT INTO Accounts ([Username], [Password], [FirstName], [LastName]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "') "
sql1 = "SELECT Count([AccountID]) FROM Accounts"
cmd = New OleDb.OleDbCommand(sql, con)
cmd1 = New OleDb.OleDbCommand(sql1, con)
Convert.ToInt32(sql1)
cmd1.ExecuteScalar()
If sql1 < 20 Then
MsgBox("Cannot accept records")
ElseIf sdr.HasRows = False Then
cmd.ExecuteNonQuery()
MsgBox("Account Added")
ElseIf sdr.HasRows = True Then
MsgBox("Username is taken")
End If
con.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
End Class
But the convert code fires an error :
Input string was in incorrect format
But if I delete the convert code it gives me the error
Conversion from string "SELECT Count([AccountID]) FROM A" to type 'Double' is not valid."
Help me please.
TIA
I dont know VB all that well, this is from the top of my head. Your trying to convert your SQL text, which will never work. Try something like this:
dim result as object
result = cmd1.ExecuteScalar()
dim count as int
count = Convert.ToInt32(result)
If count < 20 Then

Data not updated correctly

i got 2 forms... Dress_Price is for displaying the data form database ( MS Access 2007 ) another form,Edit_Dress is to edit and update the database..
the code successfully updated the data based on the changes from the form Edit_Dress.. but there is 2 problems -
the dgvCustomerDressPrice did not refreshed after updating..
there is "space" being added to the record after updated..
before update price value
Dress_Name = "Tuxedo" Dress_Price = "150"
after update price value
Dress_Name = " Tuxedo" Dress_Price = " 250"
the "space" keeps being added up everytime i update the record... so the search function cant work properly because of the space..
code on Dress_Price :-
Private Sub Dress_Price_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\TMS Final\TMS Final\db\db_TMS.accdb"
con.Open()
dgvCustomerDressPrice()
End Sub
Private Sub dgvCustomerDressPrice()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDb.OleDbDataAdapter
da = New OleDb.OleDbDataAdapter("SELECT * FROM tbl_dress", con)
da.Fill(dt)
dgvDressPrice.DataSource = dt.DefaultView
dgvDressPrice.SelectionMode = DataGridViewSelectionMode.FullRowSelect
con.Close()
End Sub
Private Sub btnEditDress_Click(sender As Object, e As EventArgs) Handles btnEditDress.Click
If dgvDressPrice.Rows.Count > 0 Then ' when user click a row, any query for database will based on Order_ID
If dgvDressPrice.SelectedRows.Count > 0 Then
Dim intDressID As Integer = dgvDressPrice.SelectedRows(0).Cells("Dress_ID").Value
Try
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM tbl_dress WHERE Dress_ID =" & intDressID, con)
' the record that will be edited is based on the Customer_ID of particular row clicked
Dim dt As New DataTable
da.Fill(dt)
Edit_Dress.txtDressID.Text = intDressID
Edit_Dress.txtDressName.Text = dt.Rows(0).Item("Dress_Name")
Edit_Dress.txtDressPrice.Text = dt.Rows(0).Item("Dress_Price")
' pass the data from tbl_user into each represented field
Catch ex As Exception
MessageBox.Show("Failed to edit data ! System eror : " & ex.ToString, "Eror !", MessageBoxButtons.OK)
End Try
End If
End If
Edit_Dress.Show()
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM tbl_dress WHERE Dress_Name like '" & txtSearch.Text & "%' ", con)
Dim dt As New DataTable
da.Fill(dt)
dgvCustomerDressPrice().DataSource = dt
con.Close()
End Sub
code on Edit_Dress :-
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\annonymous\Documents\Visual Studio 2012\Projects\TMS Final\TMS Final\db\db_TMS.accdb")
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim intDressID As Integer
intDressID = Convert.ToInt32(txtDressID.Text)
intDressID = Integer.Parse(txtDressID.Text)
Dim intDressPrice As Integer
intDressPrice = Convert.ToInt32(txtDressPrice.Text)
intDressPrice = Integer.Parse(txtDressPrice.Text)
Dim query As String = "UPDATE tbl_dress SET Dress_Name = ' " & txtDressName.Text & " ' , Dress_Price = ' " & intDressPrice & " ' WHERE Dress_ID = " & intDressID & " "
Dim cmd As New OleDb.OleDbCommand(query, con)
cmd.ExecuteNonQuery()
MessageBox.Show("Data updated !", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
Dress_Price.RefreshPriceList()
con.Close()
Me.Close()
Catch ex As Exception
MessageBox.Show("Failed to save into database ! System eror : " & ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Looking at your UPDATE method it is clear why you have a space added every time. You put it in the update string.
Dim query As String = "UPDATE tbl_dress SET Dress_Name = ' " & _
^ here
txtDressName.Text & " ' , Dress_Price = ' " & _
^here ^here
intDressPrice & " ' WHERE Dress_ID = " & intDressID & " "
^here
A part from the simple error that could be fixed removing the space, this is not the correct way to create an update command. You should use a parameterized query
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
con = New OleDb.OleDbConnection(.....)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim intDressID As Integer
intDressID = Convert.ToInt32(txtDressID.Text)
Dim intDressPrice As Integer
intDressPrice = Convert.ToInt32(txtDressPrice.Text)
Dim query As String = "UPDATE tbl_dress SET Dress_Name = ?, Dress_Price = ? " & _
"WHERE Dress_ID = ?"
Dim cmd As New OleDb.OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#p1", txtDressName.Text)
cmd.Parameters.AddWithValue("#p2", intDressPrice)
cmd.Parameters.AddWithValue("#p3", intDressID)
cmd.ExecuteNonQuery()
.....

login form using ms access in vb.net

I'm creating a login form for vb.net using ms access 2003 as database. But it only checks for the username and bypasses the password. Meaning that if the username is correct and the password doesn't jive with the username, the user can still enter the system. Here is my code:
Try
Dim NoAcc As String
Dim NoAccmod2 As String
Dim NoPas As String
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db1.mdb;Jet OLEDB:Database Password=nrew123$%^;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from admintable where AdminName= '" & TextBox4.Text & "' ", cn)
cn.Open()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
rdr.Read()
NoAcc = rdr("AdminName")
NoPas = rdr("AdminPass")
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
adminview.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox4.Clear()
TextBox3.Clear()
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
How do I do it so that it checks both username and password?
You are using a single line IF .. THEN :
If (TextBox4.Text = NoAcc And TextBox3.Text = NoPas) Then NoAccmod2 = NoAcc
so the next line will always be executed:
adminview.Show()
you have to rearrange your IF .. THEN conditions
I will share about login system in vb.net using binding navigator that less of coding. just following the link below!
http://www.tesear.com/2011/09/login-system-in-vbnet.html
You could have BOTH the uname and pword in the database and "WHERE" on both, if you get no record back, then you have your answer.
Try using System.String.Compare(String str1,String str2, Boolean ) As Integer like:
If (System.String.Compare(TextBox4.Text, NoAcc, false) And System.String.Compare(TextBox3.Text, NoPas, false)) Then NoAccmod2 = NoAcc
here is the code:
Imports System.Data
Imports System.Data.OleDb
Public Class Form5
Inherits System.Windows.Forms.Form
Dim mypath = Application.StartupPath & "\login.mdb"
Dim mypassword = ""
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mypath & ";Jet OLEDB:Database Password=" & mypassword)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Hide()
Dim sql = "SELECT UserID ,PassID FROM MYTAB WHERE USERID='" & TextBox1.Text & "' AND PASSID='" & TextBox2.Text & "'"
cmd = New OleDbCommand(sql, conn)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Try
If dr.Read = False Then
MessageBox.Show("Authentication failed...")
Me.Show()
Else
MessageBox.Show("Login successfully...")
Dim frmDialogue As New Form11
frmDialogue.ShowDialog()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Close()
End Sub
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
Me.Hide()
Dim frmDialogue As New Form1
frmDialogue.ShowDialog()
End Sub
Private Sub Form5_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Dim frm As New Form1
frm.Show()
End Sub
End Class
Try
Dim NoAcc As String
Dim NoPas As String
Dim rdr As OleDbDataReader
Dim cnn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\mobilestore.accdb;Persist Security Info=False;")
Dim cmd As OleDbCommand = New OleDbCommand("Select * from logindata where Username= '" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", cnn)
'NoAcc = TextBox1.Text
'NoPas = TextBox2.Text
cnn.Open()
rdr = cmd.ExecuteReader
If (rdr.Read()) Then
NoAcc = rdr("Username")
NoPas = rdr("password")
If (TextBox1.Text = NoAcc And TextBox2.Text = NoPas) Then
Adminpage.Show()
Me.Hide()
Else
MsgBox("Incorrect Username/Password")
TextBox1.Clear()
TextBox2.Clear()
End If
End If
Catch
MsgBox("Error logging in, please try again", MsgBoxStyle.Exclamation)
End Try
End Sub