Login form cant connect to database - database

I cannot connect to my database, i receive message "invalid user or password " even if the password is correct, what should i do anyone any idea or my code is wrong here are all my code for login form/
here is my code
Imports System.Data.SqlClient
Public Class LoginForm
Private Sub UsersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UsersBindingNavigatorSaveItem.Click
Me.Validate()
Me.UsersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
End Sub
Private Sub LoginForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DataSet1.users' table. You can move, or remove it, as needed.
Me.UsersTableAdapter.Fill(Me.DataSet1.users)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database_topdent.mdf;Integrated Security=True")
Dim command As New SqlCommand("Select * from users where User = #user and Password = #password ", connection)
command.Parameters.Add("#user", SqlDbType.VarChar).Value = UserTextBox.Text
command.Parameters.Add("#password", SqlDbType.VarChar).Value = PasswordTextBox.Text
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() <= 0 Then
MessageBox.Show("username or textbox invalid")
Else
Form1.Show()
Me.Hide()
End If
End If
End Sub
End Class

This is so confusing.
You need to check for the username and password, not just count the rows. And that table.rows.count "<=0" ? makes no sense to me.
I can see where you were going with it, but its wrong. And the question itself is not clarified enough. But assuming this is a login form. Try this>
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1_Click
Dim connection As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database_topdent.mdf;Integrated Security=True")
Dim command As New SqlCommand("Select * from [users] where [User] = #1 and [Password] = #2 ", connection)
connection.Open()
command.Parameters.AddWithValue("#1", UserTextBox.Text)
command.Parameters.AddWithValue("#2", PasswordTextBox.Text)
Using dr As SqlDataReader = command.ExecuteReader
Dim userFound As Boolean = False
Dim Name As String = ""
While dr.Read
userFound = True
Name = dr("User").ToString
End While
If userFound = True Then
MsgBox("Yes!")
ElseIf userFound = False Then
MsgBox("nay")
End If
End Using
connection.close()
End Sub
Just make sure your columns are set to vchar. I'm not able to test it, but it should work.
First you need to open the connection. Then you need to read the data in your database with the reader. then, if username and password is found, present a msg or whatever you want.
I'm sure there are better ways to do this, but here I am playing a quick good samaritan.
UPDATE #With permissions
1. Add another column named "Permissions"
2. Create a Module.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1_Click
Dim connection As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database_topdent.mdf;Integrated Security=True")
Dim command As New SqlCommand("Select * from [users] where [User] = #1 and [Password] = #2 ", connection)
connection.Open()
command.Parameters.AddWithValue("#1", UserTextBox.Text)
command.Parameters.AddWithValue("#2", PasswordTextBox.Text)
Using dr As SqlDataReader = command.ExecuteReader
Dim userFound As Boolean = False
While dr.Read
userFound = True
User1 = dr("User").ToString
Permissions = dr("Permissions").ToString
End While
If userFound = True Then
MsgBox("Yes!")
ElseIf userFound = False Then
MsgBox("nay")
End If
End Using
connection.close()
End Sub
A module
Module Module1
Public User1 As String
Public Permissions As String
End Module
And then call stuff in your forms...
For example in your main form or wherever, if you have 2 buttons on load form you can do
If Permissions = "admin" then
Button1.enabled = true
else if Permissions = "user" then
msgbox(fu)
end if

Hello here are my code for login with admin/user it works, but know i want to make permission example when user is logged in not have full access , but the admin is full access..
Here are all my codes for ' Login_Form '
Imports System.Data.SqlClient
Module Module1
Public User1 As String
Public Permissions As String
End Module
Public Class LoginForm
Private Sub UsersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UsersBindingNavigatorSaveItem.Click
Me.Validate()
Me.UsersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
End Sub
Private Sub LoginForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DataSet1.users' table. You can move, or remove it, as needed.
Me.UsersTableAdapter.Fill(Me.DataSet1.users)
If Permissions = "admin" Then
Button1.Enabled = True
ElseIf Permissions = "user" Then
Form1.RaportetToolStripMenuItem.Visible = False
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database_topdent.mdf;Integrated Security=True")
Dim command As New SqlCommand("Select * from [Table_login] where [Username] = #1 and [Password] = #2 ", connection)
connection.Open()
command.Parameters.AddWithValue("#1", UserTextBox.Text)
command.Parameters.AddWithValue("#2", PasswordTextBox.Text)
Using dr As SqlDataReader = command.ExecuteReader
Dim userFound As Boolean = False
Dim Name As String = ""
While dr.Read
userFound = True
Name = dr("Username").ToString
End While
If userFound = True Then
Form1.Show()
ElseIf userFound = False Then
MsgBox("Username or password is wrong!!!!!! ")
End If
End Using
connection.Close()
If Permissions = "user1" Then
Form1.RaportetToolStripMenuItem.Visible = False
End If
End Sub
End Class

Related

How can I Transfer an image from one picturebox to another? VB.NET & SQL

Im trying to do a login system where I store the credentials and a desired profile pic image on an access database. the desired result is that when the login matches form 1 closes and opens form 2 with the saved image loaded on a corner.
i tried doing this
Form 1 code:
Imports System.Data.OleDb
Imports System.IO
Public Class Form1
Private PictureFormat As String
Private Sub FillPictureBoxFromFile()
With OpenFileDialog1
.Filter = "(*.jpg)|*.jpg|(*.png)|*.png"
.RestoreDirectory = True
.Title = "Select a file to open"
If .ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
PictureFormat = Path.GetExtension(OpenFileDialog1.FileName)
End With
End Sub
Private cnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\Login Fase 3 Final\Login Fase 3 Final\bin\Release\DBLoginPic.mdb"
Private Sub saveimage()
Dim arrimage() As Byte
Using mstream As New System.IO.MemoryStream
If PictureFormat.ToLower = ".png" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Png)
ElseIf PictureFormat.ToLower = ".jpg" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
arrimage = mstream.GetBuffer()
Dim Filesize As Long
Filesize = mstream.Length
End Using
Using con As New OleDbConnection(cnStr),
cmd As New OleDbCommand("Insert into TBLoginPic (Imagen) Values (#Imagen)", con)
With cmd
.Parameters.Add("#Imagen", OleDbType.Binary).Value = arrimage
'.Parameters.Add("#Nombre", OleDbType.VarChar).Value = TextBox1.Text
con.Open()
.ExecuteNonQuery()
End With
End Using
End Sub
Private Function GetDataByName(name As String) As DataTable
Dim dt As New DataTable
Using conn As New OleDb.OleDbConnection(cnStr),
cmd As New OleDbCommand("Select * from TBLoginPic where Usuario= #Buscar", conn)
cmd.Parameters.Add("#Buscar", OleDbType.VarChar).Value = TBusuario.Text
conn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
End Sub
Private Sub TBusuario_TextChanged(sender As Object, e As EventArgs) Handles TBusuario.TextChanged
End Sub
Private Sub TBcontraseña_TextChanged(sender As Object, e As EventArgs) Handles TBcontraseña.TextChanged
End Sub
Private Sub BtnLoguearse_Click(sender As Object, e As EventArgs) Handles BtnLoguearse.Click
If Me.TBLoginPicTableAdapter.BuscarDatos(Me.DBLoginPicDataSet.TBLoginPic, TBusuario.Text, TBcontraseña.Text) Then
Dim dt As DataTable
Try
dt = GetDataByName(TBusuario.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
TBusuario.Text = dt(0)("Usuario").ToString
Dim arrimage = DirectCast(dt(0)("Imagen"), Byte())
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
Form2.Show()
_selectedImage = PictureBox1.Image
Me.Close()
Else
MsgBox("Datos Erroneos")
End If
End Sub
Private Sub BtnRegistrarse_Click(sender As Object, e As EventArgs) Handles BtnRegistrarse.Click
Me.TBLoginPicBindingSource.AddNew()
Me.TBLoginPicBindingSource.EndEdit()
Me.TBLoginPicTableAdapter.Update(Me.DBLoginPicDataSet)
Try
saveimage()
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
MsgBox("Image has been saved in the database")
End Sub
Private Sub BtnExaminar_Click(sender As Object, e As EventArgs) Handles BtnExaminar.Click
FillPictureBoxFromFile()
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DBLoginPicDataSet.TBLoginPic' table. You can move, or remove it, as needed.
Me.TBLoginPicTableAdapter.Fill(Me.DBLoginPicDataSet.TBLoginPic)
End Sub
Private Sub TBLoginPicBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
Me.Validate()
Me.TBLoginPicBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DBLoginPicDataSet)
End Sub
End Class
Form 2 Code:
Module imagen
Public _selectedImage As Image
Public ReadOnly Property SelectedImage As Image
Get
Return _selectedImage
End Get
End Property
End Module
Public Class Form2
Private Sub TBLoginPicBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
Me.Validate()
Me.TBLoginPicBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DBLoginPicDataSet)
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DBLoginPicDataSet.TBLoginPic' table. You can move, or remove it, as needed.
Me.TBLoginPicTableAdapter.Fill(Me.DBLoginPicDataSet.TBLoginPic)
_selectedImage = PBPerfil.Image
End Sub
Public Sub PBPerfil_Click(sender As Object, e As EventArgs) Handles PBPerfil.Click
End Sub
End Class
and get this error
System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.'
This is how form 1 looks like
This is how form 2 looks like
This is how my database looks like (don't worry there is not any personal info here))
This is where I try to send it from form 1 to 2
This is how I'm trying to receive it on form 2
any tips on what I could do better?
You need to check for nulls. If there is no data in the image column it will error when you try to manipulate it. I would suggest that you selected a default image to display if none is present in the database.
If dt(0)("Usuario") IsNot Nothing OrElse Not IsDBNull(dt(0)("Usuario")) Then
TBusuario.Text = dt(0)("Usuario").ToString
Dim arrimage = DirectCast(dt(0)("Imagen"), Byte())
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
Else
PictureBox1.Image = Image.FromFile("DefaultImage.png")
End If

Using VB.Net to Insert Data to an Access Database

Does anyone have an idea on how to update the actual access datbase file? This is my code so far and I think everything is right, but when hit the button to send the information to the actual database file it does not appear in there. Can someone help me with this? The access file I'm talking about is the one outside of the visual basic project itself, but still connected.
Code
Imports System.Data.OleDb
Public Class Form1
Dim provider As String
Dim datafile As String
Dim connString As String
Dim con As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source=G:\Music Session Database\Music Database.accdb")
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btnsubmit_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnsubmit1.Click
Me.Music_DatabaseTableAdapter.Insert(Me.songTitle.Text, Me.songArtist.Text, Me.songAlbum.Text, Me.yearReleased.Text)
Me.Music_DatabaseTableAdapter.Fill(Me.Music_DatabaseDataSet.Music_Database)
con.Open()
MsgBox("Record Added")
con.Close()
songTitle.Text = ""
songArtist.Text = ""
songAlbum.Text = ""
yearReleased.Text = ""
End Sub
Private Sub btnsumbit2_Click(sender As Object, e As EventArgs) Handles btnsumbit2.Click
Me.Play_SessionTableAdapter.Insert(Me.songTitle.Text, Me.songArtist.Text, Me.songAlbum.Text, Me.yearReleased.Text, Me.datePlayed.Text, Me.timePlayed.Text, Me.genre.Text)
Me.Play_SessionTableAdapter.Fill(Me.Music_DatabaseDataSet.Play_Session)
con.Open()
MsgBox("Record Added")
con.Close()
songTitle.Text = ""
songArtist.Text = ""
songAlbum.Text = ""
yearReleased.Text = ""
datePlayed.Text = ""
timePlayed.Text = ""
genre.Text = ""
End Sub
Private Sub btnsubmit3_Click(sender As Object, e As EventArgs) Handles btnsubmit3.Click
Me.Song_Artist_InformationTableAdapter.Insert(Me.songArtist.Text, Me.genre.Text, Me.origin.Text, Me.artistInformation.Text)
Me.Song_Artist_InformationTableAdapter.Fill(Me.Music_DatabaseDataSet.Song_Artist_Information)
con.Open()
MsgBox("Record Added")
con.Close()
songArtist.Text = ""
genre.Text = ""
origin.Text = ""
artistInformation.Text = ""
End Sub
Private Sub btnclear_Click(sender As Object, e As EventArgs) Handles btnclear.Click
songTitle.Clear()
songArtist.Clear()
songAlbum.Clear()
yearReleased.Clear()
datePlayed.Clear()
timePlayed.Clear()
genre.Clear()
artistInformation.Clear()
End Sub
Private Sub FillByToolStripButton_Click(sender As Object, e As EventArgs)
Try
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Music_DatabaseBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles Music_DatabaseBindingNavigatorSaveItem.Click
Me.Validate()
Me.Music_DatabaseBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Music_DatabaseDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Song_Artist_Information' table. You can move, or remove it, as needed.
Me.Song_Artist_InformationTableAdapter.Fill(Me.Music_DatabaseDataSet.Song_Artist_Information)
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Play_Session' table. You can move, or remove it, as needed.
Me.Play_SessionTableAdapter.Fill(Me.Music_DatabaseDataSet.Play_Session)
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Music_Database' table. You can move, or remove it, as needed.
Me.Music_DatabaseTableAdapter.Fill(Me.Music_DatabaseDataSet.Music_Database)
End Sub
Private Sub btnupdate1_Click(sender As Object, e As EventArgs) Handles btnupdate1.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Music Database]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Music_DatabaseDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
Private Sub btnupdate2_Click(sender As Object, e As EventArgs) Handles btnupdate2.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Play Session]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Play_SessionDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
Private Sub btnupdate3_Click(sender As Object, e As EventArgs) Handles btnupdate3.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Song Artist Information]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Song_Artist_InformationDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
End Class
Format of the initialization string does not conform to specification
The connString you create is not valid.
provider = "Microsoft.ACE.OLEDB.12.0"
datafile = "H:\Music Session Database\Music Database.accdb"
connString = provider & datafile
Console.WriteLine(connString)
shows
Microsoft.ACE.OLEDB.12.0H:\Music Session Database\Music Database.accdb
What you want to do is something like
connString = String.Format("Provider={0};Data Source={1}", provider, datafile)
which produces
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Music Session Database\Music Database.accdb

Cant update a record in a database

I'm making a Homework/Revision program for my coursework. I'm following this tutorial http://www.homeandlearn.co.uk/NET/nets12p9.html on how to make a database but theres something wrong with the my update button (btnUpdate)
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
txtFirstName.Text = ds.Tables("Users").Rows(inc).Item(1) = txtFirstName.Text
txtSurname.Text = ds.Tables("Users").Rows(inc).Item(2) = txtSurname.Text
txtUsername.Text = ds.Tables("Users").Rows(inc).Item(3) = txtUsername.Text
txtPassword.Text = ds.Tables("Users").Rows(inc).Item(4) = txtPassword.Text
txtClass.Text = ds.Tables("Users").Rows(inc).Item(5) = txtClass.Text
txtAdmin.Text = ds.Tables("Users").Rows(inc).Item(6) = txtAdmin.Text
txtHWP.Text = ds.Tables("Users").Rows(inc).Item(7) = txtHWP.Text
MessageBox.Show("Data updated")
End Sub
Public Class AdminEditUsers 'this is the whole code
Dim MaxRows As Integer
Dim inc As Integer
Dim con As New OleDb.OleDbConnection 'THE CONNECTION OBJECT
Dim dbProvider As String 'HOLDS THE PROVIDER
Dim dbSource As String 'HOLDS THE DATA SOURCE
Dim MyDocumentsFolder As String 'HOLDS THEDOCUMENTS FOLDER
Dim TheDatabase As String 'HOLDS THE DATABASE NAME
Dim FullDatabasePath As String 'HOLDS THE DATABASE PATH
Dim ds As New DataSet 'HOLDS A DataSet OBJECT
Dim da As OleDb.OleDbDataAdapter 'HOLDS A DataAdapter OBJECT
Dim sql As String 'HOLDS A SQL STRING
Private Sub AdminEditUsers_load(sender As Object, e As EventArgs) Handles Me.Load
'SET UP THE PROVIDER
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
'SET THE DATABASE AND WHERE THE DATABASE IS
TheDatabase = "\Visual Studio 2015/NEW_database.accdb"
MyDocumentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
FullDatabasePath = MyDocumentsFolder & TheDatabase
'SET THE DATA SOURCE
dbSource = "Data Source = " & FullDatabasePath
'SET THE CONNECTION STRING
con.ConnectionString = dbProvider & dbSource
'OPEN THE DATABASE
con.Open()
'STORE THE SQL STRING
sql = "Select * FROM tbl_user"
'PASS THE SQL STRING AND CONNECTION OBJECT TO THE DATA_ADAPTER
da = New OleDb.OleDbDataAdapter(sql, con)
'Fill the dataset with records from the database table
da.Fill(ds, "Users")
'CLOSE THE DATABASE
con.Close()
'Counts how many rows are in the table
MaxRows = ds.Tables("Users").Rows.Count
inc = -1
End Sub
Private Sub NavigateRecords()
txtFirstName.Text = ds.Tables("Users").Rows(inc).Item(1)
txtSurname.Text = ds.Tables("Users").Rows(inc).Item(2)
txtUsername.Text = ds.Tables("Users").Rows(inc).Item(3)
txtPassword.Text = ds.Tables("Users").Rows(inc).Item(4)
txtClass.Text = ds.Tables("Users").Rows(inc).Item(5)
txtAdmin.Text = ds.Tables("Users").Rows(inc).Item(6)
txtHWP.Text = ds.Tables("Users").Rows(inc).Item(7)
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
NavigateRecords()
Else
MessageBox.Show("No More Rows")
End If
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
NavigateRecords()
ElseIf inc = -1 Then
MessageBox.Show("No Records Yet")
ElseIf inc = 0 Then
MessageBox.Show("First Record")
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
NavigateRecords()
End If
End Sub
Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
NavigateRecords()
End If
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
End Sub
Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
txtFirstName.Text = ds.Tables("Users").Rows(inc).Item(1) = txtFirstName.Text
txtSurname.Text = ds.Tables("Users").Rows(inc).Item(2) = txtSurname.Text
txtUsername.Text = ds.Tables("Users").Rows(inc).Item(3) = txtUsername.Text
txtPassword.Text = ds.Tables("Users").Rows(inc).Item(4) = txtPassword.Text
txtClass.Text = ds.Tables("Users").Rows(inc).Item(5) = txtClass.Text
txtAdmin.Text = ds.Tables("Users").Rows(inc).Item(6) = txtAdmin.Text
txtHWP.Text = ds.Tables("Users").Rows(inc).Item(7) = txtHWP.Text
MessageBox.Show("Data updated")
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
End Sub
End Class
Where are you actually updating the database?
Read one more paragraph in that tutorial:
Close down your programme, then run it again. Click the Next Record button to move to the first record. It will still be "John Smith". The data you updated has been lost! So here, again, is why:
"Changes are made to the DataSet, and NOT to the Database"
The tutorial shows you how to persist those changes to the database:
da.Update(ds, "AddressBook")
Edit: It would also appear that you're making a mistake on lines like this:
txtFirstName.Text = ds.Tables("Users").Rows(inc).Item(1) = txtFirstName.Text
This may behave differently in different languages. In C# for example, I think that the result of an assignment is the value being assigned, so something like this might work. But in VB there are semantic contextual differences when using the same operator. The assignment operator (=) is also the comparison operator, depending on the context.
So I suspect that this line of code is comparing the latter two items, and assigning the result of the comparison (True or False) to the first item.
Stick with what the tutorial is showing you, just assign the value to the data:
ds.Tables("Users").Rows(inc).Item(1) = txtFirstName.Text
There's no need to also try to assign the value back to the text box where you got the value, since logically that value is already there.

Visual Basic & SQL Picturebox Controls

Using picture boxes overlaid onto an image as seen below.
Click for Form Layout
When the form loads if the student attends the class then the picturebox becomes a green tick. If the student does not attend the class the picturebox becomes blank.
Using SQL I can query the database to return all the classes that a specific student attends.
These classes are stored in an array StudentClass(n)
There are 50 classes on the timetable stored in an array AttendsClass(n). All with a default value of False.
If the student attends a class then the specific attendsclass in the array becomes True.
Once the form is loaded the user can click on a picturebox to select that class and the corresponding attendsclass in the array becomes true.
Finally the user saves the form, inserting the classes back into the database.
The problem I have is in the Sub Form4_Load at the end, I currently have to repeat the same block of code 50 times. That simply checks if the student attends the class then sets the picture box = to an image of a tick on the GUI (_new.jpg).
enter code here
If AttendsClass(1) = True Then
PictureBox1.Image = My.Resources._new
End If
If AttendsClass(2) = True Then
PictureBox2.Image = My.Resources._new
End If
If AttendsClass(3) = True Then
PictureBox3.Image = My.Resources._new
End If
If AttendsClass(4) = True Then
PictureBox4.Image = My.Resources._new
End If
Is it possible to put this into a loop to shorten my code. The code does work but its slow and lengthy so any improvements would be helpful.
Many Thanks Alex Currie
A Level Computing Student
Full Code:
enter code here
Imports System.Data.OleDb
Public Class Form4
Public con As New OleDbConnection
Public ds As New DataSet
Public da As OleDbDataAdapter
Public cb As OleDbCommandBuilder
Public constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" & Application.StartupPath & "\wma.accdb"
Public AttendsClass(50) As Boolean
Public StdID As Integer = Form2.DataGridView1.SelectedRows(0).Cells("StudentID").Value
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Forename As String = Form2.DataGridView1.SelectedRows(0).Cells("Forename").Value
Dim Surname As String = Form2.DataGridView1.SelectedRows(0).Cells("Surname").Value
Student.Text = "Student: " & Forename & " " & Surname
If Not con.State = ConnectionState.Open Then
con.ConnectionString = constring
con.Open()
End If
da = New OleDbDataAdapter("SELECT * FROM StudentClass WHERE StudentId = " & StdID, con)
da.Fill(ds, "Class")
Dim Maxrow As Integer = ds.Tables("Class").Rows.Count
Dim StudentClass(Maxrow) As Integer
For n = 1 To 50
AttendsClass(n) = False
Next
For n = 1 To Maxrow
StudentClass(n) = ds.Tables("Class").Rows(n - 1).Item(1)
For a = 0 To 50
If StudentClass(n) = a Then
AttendsClass(a) = True
End If
Next
Next
If AttendsClass(1) = True Then
PictureBox1.Image = My.Resources._new
End If
If AttendsClass(2) = True Then
PictureBox2.Image = My.Resources._new
End If
If AttendsClass(3) = True Then
PictureBox3.Image = My.Resources._new
End If
If AttendsClass(4) = True Then
PictureBox4.Image = My.Resources._new
End If
End Sub
Private Sub PictureBox1_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox1.Click
If PictureBox1.Image Is Nothing Then
PictureBox1.Image = My.Resources._new
AttendsClass(1) = True
Else
PictureBox1.Image = Nothing
AttendsClass(1) = False
End If
End Sub
Private Sub PictureBox2_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox2.Click
If PictureBox2.Image Is Nothing Then
PictureBox2.Image = My.Resources._new
AttendsClass(2) = True
Else
PictureBox2.Image = Nothing
AttendsClass(2) = False
End If
End Sub
Private Sub PictureBox4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox4.Click
If PictureBox4.Image Is Nothing Then
PictureBox4.Image = My.Resources._new
AttendsClass(4) = True
Else
PictureBox4.Image = Nothing
AttendsClass(4) = False
End If
End Sub
Private Sub PictureBox3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox3.Click
If PictureBox3.Image Is Nothing Then
PictureBox3.Image = My.Resources._new
AttendsClass(3) = True
Else
PictureBox3.Image = Nothing
AttendsClass(3) = False
End If
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If Not con.State = ConnectionState.Open Then
con.ConnectionString = constring
con.Open()
End If
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = con
'Deletes Existing Records To Be rewritten'
cmd.CommandText = "DELETE * FROM StudentClass WHERE StudentID=" & StdID
cmd.ExecuteNonQuery()
For n = 1 To 50
If AttendsClass(n) = True Then
cmd.CommandText = "INSERT INTO StudentClass (StudentID, ClassID) VALUES (" & StdID & "," & n & ")"
cmd.ExecuteNonQuery()
End If
Next
Me.Dispose()
MsgBox("Updated Successfully", MsgBoxStyle.Information, "WMA")
con.Close()
End Sub
End Class
Working example:
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles PictureBox1.Click, ...., PictureBox50.Click
Dim pic As PictureBox = CType(Controls(CType(sender, PictureBox).Name), PictureBox)
'now you have clicked picturebox
'you can change image by pic.Image = ...
'if you want picturebox index, use line below:
Dim picidx As Integer = CInt(CType(sender, PictureBox).Name.Replace("PictureBox", ""))
End Sub
VB2010Ex.

How to permanently delete a record of database from VB

Im a beginner in VB and Im trying to delete a record from a database but it doesnt let me...
they gave me this error message which i do not fully understand what it meant...
or is there any other way to delete the record permanently?
Column named userID cannot be found.
Parameter name: columnName
Heres my codes
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class frmUserManagement
Dim countID As Integer = 0
Dim conn As New SqlConnection
Dim drEmployee As SqlClient.SqlDataReader
Dim cmdEmployee As New SqlClient.SqlCommand
Dim sAdapter As New SqlDataAdapter
Dim sTable As New DataTable
Private Sub btnAddEmp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddEmp.Click
Dim tranEmployee As SqlClient.SqlTransaction
sAdapter = New SqlDataAdapter(cmdEmployee)
Dim strID As String
Dim strName As String
Dim strPosition As String
Dim strContactNo As String
Dim strAddress As String
Dim strDOB As String
Dim strGender As String
Dim strSQL As String
conn.Open()
strID = lblEmpID.Text
strName = txtEmpName.Text
strPosition = cboEmpPosition.Text
strContactNo = mskEmpDOB.Text
strDOB = mskEmpDOB.Text
strAddress = txtEmpAddress.Text
If radEmpMale.Checked Then
strGender = "Male"
Else
strGender = "Female"
End If
strSQL = "INSERT INTO Users(userID,userName,userPosition,userGender,userDOB,userAddress)" & _
"VALUES(#ID,#NAME,#POSITION,#GENDER,#DOB,#ADDRESS)"
tranEmployee = conn.BeginTransaction()
With cmdEmployee
.Transaction = tranEmployee
.CommandText = strSQL
.Parameters.AddWithValue("#ID", strID)
.Parameters.AddWithValue("#NAME", strName)
.Parameters.AddWithValue("#POSITION", strPosition)
.Parameters.AddWithValue("#GENDER", strGender)
.Parameters.AddWithValue("#DOB", strDOB)
.Parameters.AddWithValue("#ADDRESS", strAddress)
.Connection = conn
End With
Try
cmdEmployee.ExecuteNonQuery()
tranEmployee.Commit()
Catch ex As Exception
tranEmployee.Rollback()
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
End Sub
Private Sub frmUserManagement_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If mintIndex <= 9000 Then
lblEmpID.Text = "EMP" & (countID + 1).ToString("000#")
End If
Try
With conn
.ConnectionString = strConnection
.Open()
End With
With cmdEmployee
.CommandText = "SELECT * FROM Users ORDER BY userID"
.Connection = conn
End With
drEmployee = cmdEmployee.ExecuteReader()
If drEmployee.HasRows Then
While drEmployee.Read()
DataGridView1.Rows.Add(drEmployee(0), drEmployee(3), drEmployee(1), drEmployee(4), drEmployee(2), drEmployee(5))
End While
drEmployee.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
End Sub
Private Sub btnDeleteEmp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteEmp.Click
With cmdEmployee
.CommandText = "DELETE FROM Users WHERE userID = " & DataGridView1.CurrentRow.Cells(0).Value & ""
.Connection = conn
.Parameters.AddWithValue("#ID", 0)
End With
Dim rows = DataGridView1.SelectedRows
For Each row In rows
cmdEmployee.Parameters("#ID").Value = row.Cells("userID").Value
cmdEmployee.ExecuteNonQuery()
Next
drEmployee = cmdEmployee.ExecuteReader()
End Sub
Private Sub btnEditEmp_Click(sender As System.Object, e As System.EventArgs) Handles btnEditEmp.Click
lblEmpID.Enabled = False
txtEmpName.Enabled = False
grpGender.Enabled = False
End Sub
End Class
It means you do not have a column named userID in your table, are you sure it's not just ID?
You should use:
With cmdEmployee
.CommandText = "DELETE FROM Users WHERE userID = #ID"
.Connection = conn
.Parameters.AddWithValue("#ID", 0)
End With

Resources