Fill datagrid with query - vb.net

I am new to coding. Learn as I go, I want to fill a datagrid only with rows where my checkout is null
I want the specific data to show up on my datagrid that contain no checkout value. I have no clue what I am doing wrong. I am new in vb.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "D:\Projects\ezchain\ezchain\data\ex.accdb"
connec = provider & datafile
mycon.ConnectionString = connec
mycon.Open()
Dim str As String
str = "SELECT * from Keys WHERE checkout = '' "
Dim cmd As OleDbCommand = New OleDbCommand(str, mycon)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
mycon.Close()
Catch ex As Exception
MsgBox("Error")
mycon.Close()
Me.KeysTableAdapter.Fill(Me.ExDataSet.keys)
End Try
Me.KeysTableAdapter.Fill(Me.ExDataSet.keys)
End Sub
Atm nothing pops, not even exception ... o.O

Related

How do I make it so everyone has a separate account when they login

I am trying to create a login system for a revision app. However, I was wondering if there was a way where everyone can have separate accounts.
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles Btnlogin.Click
Dim sqlstring As String
sqlstring = "select * FROM login where username = '" & txtusername.Text & "'"
connection.Open()
dataadapter = New OleDb.OleDbDataAdapter(sqlstring, connection)
dt.Clear()
dataadapter.Fill(dt)
connection.Close()
If dt.Rows.Count = 0 Then
MsgBox("no such user")
Exit Sub
End If
If dt.Rows(0)(2) = Txtpassword.Text Then
Flashcard.Show()
Else
Txtpassword.Text = ""
txtusername.Text = ""
MsgBox("Invalid username and password combination")
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Register.Show()
End Sub
That's the code I have if a user already has an account.
Imports System.Data.OleDb
Public Class Register
Dim pro As String
Dim connstring As String
Dim command As String
Dim myconnection As OleDbConnection = New oledbconnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
pro = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = " insert into login ([username],[password]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("username", CType(TextBox1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("password", CType(TextBox1.Text, String)))
MsgBox("You have successfully signed up!")
Form1.Show()
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
TextBox1.Clear()
TextBox2.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
That's the code if the user presses the register button (does not have an account).
This code works where the user can succesfully login or register, but the problem is that everyone will have the same windows form. So, I was wondering if there was a way to make each windows form unique to each user?
You can declare and initialize a variable on the same line. The only information you need is if the userName and password exist in the database. Don't pull down data your don't need. You can get this with Count.
Always declare and dispose the connection and command it the method where they are used. Both of these objects need to be disposed so that their unmanaged resources can be released. Using... End Using blocks handle this.
Always use parameters to avoid sql injection. In OleDb the order that the parameters appear in the sql string must match the order that they are added to the parameters collection.
Don't open the connection until directly before the .Execute...
Private ConStr As String = "provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb" '"Your connection string"
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles Btnlogin.Click
Dim rowCount As Integer
Dim sqlstring = "select Count(*) FROM login where [username] = #UserName ANd [password] = #password;"
Using connection As New OleDbConnection(ConStr),
cmd As New OleDbCommand(sqlstring, connection)
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = txtusername.Text
connection.Open()
rowCount = CInt(cmd.ExecuteScalar)
End Using
If rowCount = 0 Then
MsgBox("no such user")
Else
Flashcard.Show()
End If
End Sub
Same ideas for the insert. A text box's Text property is always a String so you don't have to convert it.
You are not doing the parameters correctly. You are not using these parameters because the don't appear in the CommandText
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Command = " insert into login ([username],[password]) values (#UserName, #Password);"
Try
Using myconnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Command, myconnection)
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = TextBox2.Text
myconnection.Open()
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
MsgBox("You have successfully signed up!")
Form1.Show()
TextBox1.Clear()
TextBox2.Clear()
End Sub
Finally, and very important. You should never store passwords as plain text. Look into salting and encrypting.

Adapter update statement in oledb

I have a form with retrieved data form ms access database. While updating using the adapter update statement, it shows Syntax error.
The following are the connection code in form load event and update button click event.
could you please let me know whats wrong in this?
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Dim Con As New OleDbConnection()
Dim Cmd As New OleDbCommand
Dim SQL As String = "SELECT * FROM Heidelberg"
Con.ConnectionString = strConn
Try
Con.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Cmd = New OleDbCommand(SQL, Con)
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
ds = New DataSet
Adapter.Fill(ds, "testing")
MaxRows = ds.Tables("testing").Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
Dim cb As New OleDb.OleDbCommandBuilder(Adapter)
ds.Tables("testing").Rows(inc).Item(5) = TextBox1.Text
ds.Tables("testing").Rows(inc).Item(2) = TextBox2.Text
ds.Tables("testing").Rows(inc).Item(3) = TextBox3.Text
ds.Tables("testing").Rows(inc).Item(4) = TextBox4.Text
Try
Adapter.Update(ds, "testing")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
You have way too many commands in your Form.Load.
One
Dim Cmd As New OleDbCommand
Two
Cmd = New OleDbCommand(SQL, Con)
Three
Adapter.SelectCommand = New OleDbCommand(SQL, Con)
Every time you use the New keyword, you create another command.
If you are only dealing with a single table, you don't need a DataSet. The extra object adds extra weight and complicates the code a bit.
Private inc As Integer
Private Adapter As New OleDbDataAdapter
Private MaxRows As Integer
Private dat As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\DESKTOP\VBATESTING\ADPE Project\Project Tables\ADPE_Table.accdb"
inc = 0
Using Con As New OleDbConnection(strConn)
Using Cmd As New OleDbCommand("SELECT * FROM Heidelberg;", Con)
Adapter.SelectCommand = Cmd
Try
Adapter.Fill(dat)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
MaxRows = dat.Rows.Count
Label1.Text = "Total Records :" & MaxRows
NavigateRecords()
End Sub
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
dat.Rows(inc).Item(5) = TextBox1.Text
dat.Rows(inc).Item(2) = TextBox2.Text
dat.Rows(inc).Item(3) = TextBox3.Text
dat.Rows(inc).Item(4) = TextBox4.Text
Dim cb As New OleDbCommandBuilder(Adapter)
'This will take care of any spaces that you have in column names.
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Try
Adapter.Update(dat)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

VB.NET SQL Database locked

My data table is loaded in 2 places, a DataGridView and a ComboBox
The ComboBox is to select a record to edit (a TextBox to enter a new value)
And the DataGridView is to see the changes (I gave up (for now) updating directly from the DataGridView)
Private Sub EditLoc_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
con.Open()
Dim sql = Nothing
sql = "SELECT Location FROM Location"
Dim cmdDataGrid As SQLiteCommand = New SQLiteCommand(sql, con)
Dim da As New SQLiteDataAdapter
da.SelectCommand = cmdDataGrid
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
Dim readerDataGrid As SQLiteDataReader = cmdDataGrid.ExecuteReader()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try ' TRY CATCH for combobox
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Location FROM Location"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBox1.Items.Add(dr.GetString(0))
Loop
If ComboBox1.Items.Count > 0 Then
ComboBox1.SelectedIndex = 0 ' The first item has index 0 '
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This works perfectly
Picture
The problem is when I click Save, the app hangs a while, and then I get the "Database is locked" error picture
Here is the code for the Save button:
Private Sub Savebtn_Click(sender As Object, e As EventArgs) Handles Savebtn.Click
Try
con.Open()
cmd = con.CreateCommand
cmd.CommandText = "UPDATE Location set Location = '" & TextBox1.Text & "' WHERE Location = '" & ComboBox1.Text & "'"
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Thanks for the help
I fixed this problem by removing all "cmd.Dispose()", "da.Dispose()" and "con.Close()" from the code, leaving them ONLY in
Private Sub Closebtn_Click(sender As Object, e As EventArgs) Handles Closebtn.Click
da.Dispose()
cmd.Dispose()
con.Close()
Dim fems As New EMS
fems.Show()
Me.Close()
End Sub
On Form Load I have
Private Sub EditLoc_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.Open()
Call pull()
End Sub
And the Pull sub has all the rest...
Private Sub pull()
Try
Dim sql = Nothing
sql = "SELECT Location FROM Location"
Dim cmdDataGrid As SQLiteCommand = New SQLiteCommand(sql, con)
da.SelectCommand = cmdDataGrid
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
Dim readerDataGrid As SQLiteDataReader = cmdDataGrid.ExecuteReader()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Try ' TRY CATCH for combobox
cmd.Connection = con
cmd.CommandText = "SELECT Location FROM Location"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBox1.Items.Add(dr.GetString(0))
Loop
If ComboBox1.Items.Count > 0 Then
ComboBox1.SelectedIndex = 0 ' The first item has index 0 '
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
And here is my Save button
Private Sub Savebtn_Click(sender As Object, e As EventArgs) Handles Savebtn.Click
If Not TextBox1.Text = Nothing Then
Try
cmd = con.CreateCommand
cmd.CommandText = "UPDATE Location set Location = '" & TextBox1.Text & "' WHERE Location = '" & ComboBox1.Text & "'"
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Call pull()
TextBox1.Text = Nothing
End If
End Sub
Now everything is working, no errors!
Calling pull() after saving will update the DataGridView
Thanks for the help

'An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll' error message?

I have made a quiz that is supposed to save the students name and score to the correct table in an access database. There are 3 tables. I have tried to connect and code the database but I keep getting the following error message:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "INSERT INTO Class1 ([StudentScor" to type 'Double' is not valid.
I have tried to find solutions to this error however, I don't fully understand. Here is my code for the save button which should save the name and score to the correct table:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
StudentClass = cbSelectClass.SelectedItem
Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
DataFile = IO.Path.Combine(Application.StartupPath, "StudentScores.accdb")
ConnString = Provider & DataFile
If StudentClass = "Class1" Then
Strng = "INSERT INTO Class1 ([StudentScores], [Score]) Values('" + CType(txtName.Text, String) + CType(Score, Integer)
ElseIf StudentClass = "Class2" Then
Strng = "INSERT INTO Class2 ([Student Scores], [Score]) Values('" + CType(txtName.Text, String) + CType(Score, Integer)
ElseIf StudentClass = "Class3" Then
Strng = "INSERT INTO Class3([StudentScores], [Score]) Values('" + CType(txtName.Text, String) + CType(Score, Integer)
End If
MyConnection.ConnectionString = ConnString
Dim cmd As OleDbCommand = New OleDbCommand(Strng, MyConnection)
MyConnection.Open()
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
MyConnection.Close()
txtName.Clear()
Catch ex As Exception
MsgBox(ex.Message)
cmd.Dispose()
MyConnection.Close()
End Try
Me.Close()
End Sub
You have a lot of unnecessary CType casting going on. Textbox.Text is already of type string. You don't want to cast Score to an Integer, because you are concatenating to a string. Also, get used to the String.Format function, as it'll help code readability and will help you find your mis-named DB column name. Don't be afraid of white space for readability:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Const SQL_INSERT As String = "INSERT INTO {0} (StudentScores, Scores) VALUES ('{1}', {2})"
Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
DataFile = IO.Path.Combine(Application.StartupPath, "StudentScores.accdb")
ConnString = Provider & DataFile
Dim sql As String = String.Format(SQL_INSERT, cbSelectClass.SelectedItem, txtName.Text.Trim, Score.ToString)
MyConnection.ConnectionString = ConnString
Dim cmd As OleDbCommand = New OleDbCommand(sql, MyConnection)
MyConnection.Open()
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
MyConnection.Close()
txtName.Clear()
Catch ex As Exception
MsgBox(ex.Message)
cmd.Dispose()
MyConnection.Close()
End Try
Me.Close()
End Sub
Now, you'll have to look into SQL Injection to correct that, and you should use the Using statement to initialize the Connection and Command objects.

Checking a PIN number is correct according to it's card number

I'm currently working on an assignment for college that I'm really stuck on. I have to create an application to simulate an ATM machine using Visual Basic 2010. I'm currently stuck trying to check whether the PIN number entered in the text box is correct for the card number selected in the combo box. If the user enters the PIN incorrectly three times, the card is confiscated. I am getting an error message at the moment saying "Object variable or With block variable not set". Below is the code I have written:
Imports System.Data.OleDb
Public Class PinEntry
Public connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\ben\Documents\Programming\Year 2\Visual Studio\Assignment2\BankOfGlamorgan\EDP2011-BoG.mdb"
Friend connectionBG As New OleDbConnection
Dim ds As New DataSet
Dim da As New OleDbDataAdapter
Dim commandCardNumber As New OleDbCommand()
Dim dr As OleDbDataReader
Dim pinErrorCount As Integer
Dim ATMCardsBindingSource As New BindingSource
Dim SqlCommandCheckPIN As New OleDbCommand
Dim SqlCommandConfiscate As New OleDbCommand
Private Sub PinEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connectionBG.ConnectionString = connectionString
commandCardNumber.Connection = connectionBG
commandCardNumber.CommandType = CommandType.Text
commandCardNumber.CommandText = "SELECT cardNumber FROM ATMCards"
Try
connectionBG.Open()
da.SelectCommand = commandCardNumber
da.Fill(ds, "ATMCards")
cmbCardNumber.DataSource = ds.Tables("ATMCards")
cmbCardNumber.DisplayMember = "cardNumber"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub btnEnterPin_Click(sender As Object, e As EventArgs) Handles btnEnterPin.Click
Try
Me.connectionBG.Open()
Dim PIN As String
Dim cardNo As String
PIN = Me.txtPIN.Text
cardNo = Me.ATMCardsBindingSource.Current("cardNumber")
Me.SqlCommandCheckPIN.Parameters("#PIN").Value = PIN
Me.SqlCommandCheckPIN.Parameters("#cardNumber").Value = cardNo
Dim dr As OleDbDataReader = Me.SqlCommandCheckPIN.ExecuteReader()
If dr.HasRows And pinErrorCount <= 2 Then
My.Forms.Menu.ShowDialog()
dr.Close()
pinErrorCount = 0
txtPIN.Text = ""
ElseIf pinErrorCount = 2 Then
dr.Close()
MessageBox.Show("PIN Entered Incorrectly Three Times Card Now Confiscated", "Card Taken", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
cardNo = Me.ATMCardsBindingSource.Current("cardNumber")
Me.SqlCommandConfiscate.Parameters("#cardNumber").Value = cardNo
Me.SqlCommandConfiscate.ExecuteNonQuery()
Else
pinErrorCount = pinErrorCount + 1
MessageBox.Show("Incorrect PIN Please Try Again.", "Incorrect PIN", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtPIN.Text = ""
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Me.connectionBG.Close()
End Try
End Sub
End Class
Updated code below:
Imports System.Data.OleDb
Public Class PinEntry
Public connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\ben\Documents\Programming\Year 2\Visual Studio\Assignment2\BankOfGlamorgan\EDP2011-BoG.mdb"
Friend connectionBG As New OleDbConnection
Dim ds As New DataSet
Dim da As New OleDbDataAdapter
Dim commandCardNumber, commandPinNumber As New OleDbCommand()
Dim dr As OleDbDataReader
Dim pinErrorCount, cardNumber, PIN As Integer
Dim oForm As Menu
Dim userInput As String
Private Sub PinEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connectionBG.ConnectionString = connectionString
commandCardNumber.Connection = connectionBG
commandCardNumber.CommandType = CommandType.Text
commandCardNumber.CommandText = "SELECT cardNumber FROM ATMCards"
commandPinNumber.Connection = connectionBG
commandPinNumber.CommandType = CommandType.Text
commandPinNumber.CommandText = "SELECT PIN FROM ATMCards WHERE cardNumber = ?"
Try
connectionBG.Open()
da.SelectCommand = commandCardNumber
da.Fill(ds, "ATMCards")
cmbCardNumber.DataSource = ds.Tables("ATMCards")
cmbCardNumber.DisplayMember = "cardNumber"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub btnEnterPin_Click(sender As Object, e As EventArgs) Handles btnEnterPin.Click
cardNumber = Convert.ToInt16(cmbCardNumber.Text)
commandPinNumber.Parameters.Add(New OleDbParameter())
commandPinNumber.Parameters(0).Value = cardNumber
Try
connectionBG.Open()
dr = commandPinNumber.ExecuteReader()
While dr.Read()
PIN = dr.Item("PIN").ToString
End While
dr.Close()
If PIN = userInput Then
MsgBox("Correct PIN")
Else
MsgBox("Incorrect PIN")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub txtPIN_TextChanged(sender As Object, e As EventArgs) Handles txtPIN.TextChanged
userInput = txtPIN.Text
End Sub
End Class
OleDBCOmmand objects are typically used in a more disposable way than as module level variables. In order to work, they also need a SQL string and a Connection object associated with them. Ex:
Dim sql As String = "SELECT etc etc etc WHERE something = ?"
Using cmd As New OleDbCommand(Sql, dbCon)
cmd.Parameters.AddWithValue("#p1", myVar)
cmd.Parameters.AddWithValue("#p2", myVar)
Dim rdr As OleDbDataReader = cmd.ExecuteReader
If rdr.HasRows Then
' do something interesting
End If
End Using
Here, both the SQL and DB Connection are associated with the Command Object when it is created. The Using block assures it is properly disposed of when we are done with it.
Also, OleDbCommand objects do not support named parameters. Usually, it just ignores them. The right way for Paramters is shown (ie AddWithValue) where you replace each ? placeholder in the SQL string in order with the actual value. Do be sure the data type matches. If PIN is a number, you must add a number, not Text.
For the SQL, you are testing the PIN entered against a card number, so those are the param values. Depending on how you construct the SQL you can either see if the PIN in the DB matches the one they gave OR just see if you get any rows back.