Register Form Issues VB.Net - vb.net

I am having an issue when I am setting up this Register form.
My current code is this:
Public Class Form2
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, con)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, con)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class
I am having the issue at connection.open(). The error that I am having is
The ConnectionString property has not been initialized.
I have been trying for the past hour to find different ways to write to the database but to no prevail and I cannot figure this out.
[In response to Steve
My code after editing and still the same error
Imports System.Data.OleDb
Public Class Form2
Dim connection As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, connection)
Dim connStr As String
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDb.OleDbConnection(connStr)
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
TheDatabase = "\Robocopy_Test.accdb"
MyDocumentsFolder = "C:\Users\Dan\Desktop\WindowsApplication2"
FullDatabasePath = MyDocumentsFolder & TheDatabase
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
sql = "SELECT * FROM Robocopy"
da = New OleDb.OleDbDataAdapter(sql, connection)
'da.Fill(ds, "Robocopy")
MessageBox.Show("Databse is Open")
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
'DBTest.Text = ds.Tables("Robocopy").Rows(0).Item(1)
'DBTestP.Text = ds.Tables("Robocopy").Rows(0).Item(2
sql = "INSERT INTO Robocopy(username,password) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
cmd.Connection = connection
connection.Open()
cmd.CommandText = sql
da.InsertCommand = cmd
da.InsertCommand.ExecuteNonQuery()
connection.Close()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
connection.Close()
MessageBox.Show("Database Is now Closed")
End Sub
End Class

Global variables could be very ....evil. Expecially if you name them with the same name of a local variable.
Me.connection is not the same variable connection declared as local variable inside the sub. You set the connection string on the global variable then use the local variable without any connection string
Change these two lines
Me.connection.ConnectionString = dbProvider & dbSource
Me.connection.Open()
removing the Me.
connection.ConnectionString = dbProvider & dbSource
connection.Open()
and don't open the connection two times.
In any case, you don't need the adapter at all to execute an insert command
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Dan\Desktop\WindowsApplication2\Robocopy_Testaccdb1.accdb"
Dim connStr = dbProvider & dbSource
DBTest1 = DBTest.Text
DBTestP1 = DBTestP.Text
sql = "INSERT INTO Robocopy(username,[password]) VALUES('" & DBTest1 & "','" & DBTestP1 & "')"
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = new OleDb.OleDbCommand(sql, connection )
connection.Open()
cmd.ExecuteNonQuery()
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Using
End Using
End Sub
I see also that you have commented out the Parameterized approach to your query. Please do yourself a favour and restore as soon as possible the parameters logic. It is a lot more safe and avoids numerous errors
Finally Password is a reserved keyword in Access.Use square brakets around it otherwise you will see an unexplicable "Syntax Error" in your insert command

Related

Forgot Password Form Issues VB.net

I am trying to create a forgot password screen for my application. I am using the tab control for the different pages. My current code is able to create a user but it is able to create duplicates (Which is an issue needed to be rectified) I then have an issue with the forget password screen not working completely.
My code is:
Imports System.Data.OleDb
Public Class Form2
Dim connection As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim MyDocumentsFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim DBTest1 As String
Dim DBTestP1 As String
Dim cmd As New OleDbCommand(sql, connection)
Dim connStr As String
Dim usernamevalid As Integer
Dim passwordvalid As Integer
Public Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
If User.Text.Length < 4 Then
usernamevalid = 0
ElseIf User.Text.Length > 4 Then
usernamevalid = 1
End If
If Pass.Text.Length < 5 Then
passwordvalid = 0
ElseIf Pass.Text.Length > 5 Then
passwordvalid = 1
End If
If usernamevalid = 0 Then
MsgBox("Username Must Be At Least 5 Characters")
End If
If passwordvalid = 0 Then
MsgBox("Password Must Be At Least 5 Characters")
End If
If passwordvalid And usernamevalid = 1 And Pass.Text = RePass.Text Then
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Daniel\Documents\Robocopy.accdb"
Dim connStr = dbProvider & dbSource
DBTest1 = User.Text
DBTestP1 = Pass.Text
sql = "INSERT INTO Robocopy(username,[password],sq,sqa) VALUES('" & DBTest1 & "','" & DBTestP1 & "','" & SQREG.Text & "', '" & SQAREG.Text & "')"
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = New OleDb.OleDbCommand(sql, connection)
connection.Open()
cmd.ExecuteNonQuery()
connection.Close()
MsgBox("User Created!")
'With cmd.Parameters
'.AddWithValue("usernamer", DBTest.Text)
'.AddWithValue("password", DBTestP.Text)
'.AddWithValue("email", txtsub.text)
'.AddWithValue("contactnum", txtau.text)
'End With
'cmd.ExecuteNonQuery()
End Using
End Using
ElseIf Not Pass.Text = RePass.Text Then
MsgBox("Passwords did not match")
End If
End Sub
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim result = MessageBox.Show(" Are you sure you want to quit", "Are you sure?", MessageBoxButtons.YesNoCancel)
Me.Close()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If NewPass.Text = ReNewPass.Text Then
Try
connection.Open()
cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
cmd.ExecuteNonQuery()
MessageBox.Show("PASSWORD CHANGE SUCCESSFULLY")
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
End Class
The exception it catches is The ConnectionString property has not been initialized
Currently I changed my code to what I think you mean:
Button4's code has been changed as such:
Private Sub ResetPassword_Click(sender As Object, e As EventArgs) Handles ResetPassword.Click
If NewPass.Text = ReNewPass.Text Then
Using connection = New OleDb.OleDbConnection(connStr)
Using cmd = New OleDb.OleDbCommand(sql, connection)
connection.Open()
cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
cmd.ExecuteNonQuery()
MessageBox.Show("PASSWORD CHANGE SUCCESSFULLY")
connection.Close()
End Using
End Using
End If
End Sub
I now get the error for cmd = New OleDbCommand("update robocopy set [password] = '" & NewPass.Text & "' where username = '" & UserFGT.Text & "'", connection)
I am getting the error for cmd where it says 'Read Only' Variable cannot be the target of assignment
The only thing I can see wrong with the connection string are extra spaces after 'Data Source='.
Here's an example from connectionstrings.com:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;Persist Security Info=False;

how to add data in sql database with datagridview

heres my code in adding data to sql database
Dim ConStr As String = "Data Source=SYSTEMS-LAPTOP\DEVSQL;Initial Catalog=ContactDB;Persist Security Info=True;User ID=sa;Password=P#ssw0rd123"
Dim sql As String = "SELECT * FROM dataContactDB"
Dim sqlCon As New SqlConnection
Dim sqlCmd As New SqlCommand
Dim sqlAdapter As SqlDataAdapter
Dim sqlBuilder As SqlCommandBuilder
Dim sqlDataset As DataSet
Dim sqlTable As DataTable
this code loads my data in datagridview from sqldatabase
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
sqlCon = New SqlConnection(ConStr)
sqlCon.Open()
sqlCmd = New SqlCommand(sql, sqlCon)
sqlAdapter = New SqlDataAdapter(sqlCmd)
sqlBuilder = New SqlCommandBuilder(sqlAdapter)
sqlDataset = New DataSet
sqlAdapter.Fill(sqlDataset, "dataContactDB")
sqlTable = sqlDataset.Tables("dataContactDB")
sqlCon.Close()
dgData.DataSource = sqlDataset.Tables("dataContactDB")
dgData.ReadOnly = True
dgData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
my codes in adding data to sqldatabase
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
sqlCon.Open()
sqlCmd.CommandText = "insert into dataContactDB(con_Name,con_Phone,Address,Company,Gender) values('" & txtName.Text & "','" & txtPhone.Text & "','" & txtAddress.Text & "','" & txtCompany.Text & "','" & txtGender.Text & "')"
sqlCmd.ExecuteNonQuery()
sqlCon.Close()
End Sub
all i want to do is when you add data in sqldatabase. datagridview will retrieve the new added data and add it on its list. every time i add data . datagridview didnt show my recent added data, how do i do that?
You simply have to reload the data in grid. Put all code the in a function named LoadMyGrid, that you have written in frm_load. Now call this method from frm_load. Also call same method in your button click event in the last line.

Changing DataGridview after filter combobox

I'm trying to refill my DataGridView after a filter selection in a combobox.
Here is my code where I try...at this moment the code is clearing the DataGridview and just fill only on row with only 1 cell..KlantID = 7
Any idea?
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
klantid = ComboBox1.SelectedValue
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim SQLstr As String
SQLstr = "SELECT * FROM tblKlant WHERE KlantID = #klantid"
Dim cmd As New OleDbCommand(SQLstr, myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(ds, "tblKlant")
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblKlant"
DataGridView1.Refresh()
End Sub
Why are you populating records on every combobox_SelectionChange event execution. Try to filter your data only instead of query execution.
And, better to use SelectedValueChanged event instead of SelectionChange.
Private Sub form_Load(sender As Object, e As EventArgs) Handles Me.Load
//Fill your data here with DataView
Dim myConnection As OleDbConnection
Dim DBpath As String = "C:\Facturatie\CharelIjs.accdb"
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DBpath & ";Persist Security Info=True"
myConnection = New OleDbConnection(sConnectionString)
myConnection.Open()
Dim cmd As New OleDbCommand("SELECT * FROM tblKlant", myConnection)
Dim da As New OleDbDataAdapter(cmd)
Dim dt As New DataTable() 'Dont use dataset if your are not relating more than one tables
cmd.Parameters.Add("#klantid", OleDbType.VarChar)
cmd.Parameters(0).Value = klantid
Try
da.Fill(dt)
dt.TableName = "tblKlant"
cmd.ExecuteNonQuery()
DataGridView1.DataSource = dt.DefaultView
DataGridView1.DataMember = "tblKlant"
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
Return
End Try
End Sub
Private Sub combobox_SelectedValueChanged(sender As Object, e As EventArgs) Handles combobox.SelectedValueChanged
IF combobox.SelectedValue IsNot Nothing Then
Dim dv As DataView = DirectCast(DataGridView1.DataSource, DataView)
dv.RowFilter = "KlantID=" + combobox.SelectedValue.ToString()
Else
dv.RowFilter = vbNullString
End IF
End Sub

system.data.oledb.oledbexception:Syntax error in INSERT INTO Statement

I have a Project in VB.NET as follows
Public Class MCARegis
Dim con As New OleDb.OleDbConnection()
Private Sub MCARegis_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim da As OleDb.OleDbDataAdapter
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
MsgBox("opened")
End Sub
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
Try
Dim da As OleDb.OleDbDataAdapter
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
Dim sqlquery As String = "INSERT INTO MCA (URno,SName,Fname,CAddress,)" + "VALUES (" & CInt(txtUrn.Text) & ",'" & txtName.Text & "','" & txtFname.Text & "','" & txtCAdd.Text & "');"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("Record Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I am getting an error when i try to add values at the Insert into statement any suggestions on this?
system.data.oledb.oledbexception:Syntax error in INSERT INTO Statement at system.data.oledb.command.exceutecommandtexterrorhandling(oledbhresult hr)
at systems.data.oledb.oledbcommand.executecommandtext(object&executeresult)......
at system.data.oledb.oledbcomamand.executenonquery()
at line 29.
Thanks in Advance....
Replace "INSERT INTO MCA (URno,SName,Fname,CAddress,)" by "INSERT INTO MCA (URno,SName,Fname,CAddress)". You have specified a redundant comma

Visual Basic 2008 New Search Query

I'm trying to do a search through an access database I added to a project but I get this error: An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll"
Additional information: No value given for one or more required parameters.
The idea was to search the database for text entered into a textbox, then display the information on that row within more text boxes.
The code dr = cmd.ExecuteReader is also highlighted as an issue when debugging. I'm using visual basic 2008, and quite new to the whole coding scene so explanations as to why the issue has occurred would be appreciated!
Imports System.Windows.Forms
Imports System.Data.OleDb
Public Class frmSearch
Public con As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Dim dbProvider As String
Dim dbSource As String
Dim BillingSystemFolder As String
Dim TheDatabase As String
Dim FullDatabasePath As String
Private Sub frmSearch_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'BillingdatabaseDataSet.BillingInfo' table. You can move, or remove it, as needed.
Me.BillingInfoTableAdapter.Fill(Me.BillingdatabaseDataSet.BillingInfo)
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
'Setup the provider
TheDatabase = "/billingdatabase.accdb"
BillingSystemFolder = Application.StartupPath
FullDatabasePath = BillingSystemFolder & TheDatabase
'Set the database and the location of it
dbSource = "Data Source = " & FullDatabasePath
'Set the data source
con.ConnectionString = dbProvider & dbSource
'Set the connection string
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
txtJobNum.Clear()
txtName.Clear()
txtSurname.Clear()
Dim str As String
str = "SELECT * FROM BillingInfo WHERE (Code = " & CodeText.Text & ")"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
dr = cmd.ExecuteReader
While dr.Read()
txtSurname.Text = dr("Surname").ToString
txtName.Text = dr("First Name").ToString
txtJobID.Text = dr("Customer ID").ToString
End While
con.Close()
End Sub
End Class
Probably the field Code is a text field. In this case when you want to search using a particular value for that field you should enclose the value between single quotes.
Something like this
str = "SELECT * FROM BillingInfo WHERE (Code = '" & CodeText.Text & "')"
However this is really a bad practice because this allows to create an Sql Injection attack or it will simply fail because your value contains a single quote.
The correct method is using a parameterized query like this
str = "SELECT * FROM BillingInfo WHERE (Code = #p1)"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = CodeText.Text
dr = cmd.ExecuteReader