I've been working on a computing project in Visual Basic 2010 and I've encountered a error and I cannot find the problem causing it.
Whenever I try to save to my database I get a error in my OleDBConnection.vb form with the following
This is my Code
Class OleDbConnection
Private _p1 As Object
Sub New(ByVal p1 As Object)
' TODO: Complete member initialization
_p1 = p1
End Sub
Sub Close()
Throw New NotImplementedException
End Sub
Sub Open()
**Throw New NotImplementedException**
End Sub
End Class
my original code for the saving of the project to the database is
Public Class AddClass
Public Shared connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\Sami\Desktop\F454\VB_PrototypeDB.accdb;Persist Security Info=False;"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub DataView()
Throw New NotImplementedException
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
Me.Hide()
MMenu.Show()
End Sub
Private Sub PictureBox2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox2.Click
Dim cn As New OleDbConnection(connectionString)
cn.Open()
Dim ClassName As String = TextBox1.Text
Dim Subject As String = ComboBox1.Text()
Dim cmd As New OleDbCommand("INSERT INTO Class (ClassName, Subject) VALUES ('" & ClassName & "', '" & Subject & "') ')", cn)
cmd.ExecuteNonQuery()
cn.Close()
Call MsgBox("Student Has Been Saved", 0, "Student Database")
End Sub
End Class
Related
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
I'm currently operating Visual Studio 2012. I have a "URL Scanner" form where once a url is entered into a text box, four web browsers opens up and inputs the url into the site and displays.
My problem is this, I get multiple script error pop ups with a error box that states
"Object doesn't support property or method 'getElementsByClassName'".
I tried looking up related resolutions but can't get it to work. I'm quite new to VB and hope someone could correct my mistake.
Class MainWindow
Dim WithEvents ScriptWindow As WebBrowser
Private Sub Enter_Click(sender As Object, e As RoutedEventArgs) Handles Enter1.Click
If TextBox1.Text = "" Then
MessageBox.Show("Please type a target URL in the space provided!")
Else
'Dim file As System.IO.StreamWriter
Dim theDate As Date
theDate = Format(Now(), "short date")
Textboxdate.Text = theDate
' file = My.Computer.FileSystem.OpenTextFileWriter("URLlogs.txt", True)
'file.WriteLine(TextBox1.Text & " | Date of search: " & Textboxdate.Text)
'file.Close()
Dim path As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\URLlogs.txt"
Dim writer As New System.IO.StreamWriter(path, True)
writer.WriteLine(TextBox1.Text & " | Date of search: " & Textboxdate.Text)
writer.Close()
WebBrowser1.Navigate("https://www.talosintelligence.com/reputation_center/lookup?search=" & TextBox1.Text)
WebBrowser2.Navigate("https://www.ssllabs.com/ssltest/analyze.html?d=" & TextBox1.Text)
WebBrowser3.Navigate("https://sitecheck.sucuri.net/results/" & TextBox1.Text)
WebBrowser4.Navigate("https://quttera.com/detailed_report/" & TextBox1.Text)
End If
End Sub
Private Sub Reset_Click(sender As Object, e As RoutedEventArgs) Handles Reset.Click
TextBox1.Text = ""
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As TextChangedEventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub SuppressScriptErrors()
If (WebBrowser1.Document IsNot Nothing) Then
ScriptWindow = WebBrowser1.Document.Window
End If
End Sub
Private Sub SuppressScriptErrors2()
If (WebBrowser2.Document IsNot Nothing) Then
ScriptWindow = WebBrowser2.Document.Window
End If
End Sub
Private Sub SuppressScriptErrors3()
If (WebBrowser3.Document IsNot Nothing) Then
ScriptWindow = WebBrowser3.Document.Window
End If
End Sub
Private Sub SuppressScriptErrors4()
If (WebBrowser4.Document IsNot Nothing) Then
ScriptWindow = WebBrowser4.Document.Window
End If
End Sub
Private Sub Startpage1_Click(sender As Object, e As RoutedEventArgs) Handles Startpage1.Click
Me.Hide()
Dim startwindow As New StartWindow
startwindow.Show()
End Sub
Private Sub SearchHistory1_Click(sender As Object, e As RoutedEventArgs) Handles SearchHistory1.Click
Dim path As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\URLlogs.txt"
If System.IO.File.Exists(path) = True Then
Process.Start(path)
Else
MessageBox.Show("Please generate a search before proceeding")
End If
End Sub
End Class
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
I am having a problem but don't know exactly what is wrong with it my code is below:
Imports System.Data.SqlClient
Imports System.Data
Public Class FormAdd
Private Sub btnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click
FormAdmin.Show()
Me.Hide()
End Sub
Private Sub btnAdd_Click(ByRef Success As String, ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Call AddUser(Success)
MsgBox(" " & Success & " ")
End Sub
Private Sub AddUser(ByRef Success As String)
lblAdmin.Text = Str(chkAdminAccount.Checked)
Dim con As New SqlConnection
Dim lrd As SqlDataReader
Dim inscmd As New SqlCommand
inscmd.Parameters.AddWithValue("#Username", txtUsername.Text.Trim())
txtUsername.Text = txtUsername.Text
inscmd.Parameters.AddWithValue("#Password", txtPassword.Text.Trim)
txtPassword.Text = txtPassword.Text
inscmd.Parameters.AddWithValue("#Name", (txtName.Text.Trim))
txtName.Text = txtName.Text
inscmd.Parameters.AddWithValue("#AdminAccount", lblAdmin.Text.Trim)
lblAdmin = lblAdmin
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Alwyn\Desktop\Computing A2 Alwyn\Comp4ProjectRoomBookingSystem\WindowsApplication1\WindowsApplication1\Database1.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Try
con.Open()
inscmd.CommandText = "INSERT INTO Admin (Username, Password, Name, AdminAccount) VALUES (#Username, #Password, #Name, #AdminAccount)"
inscmd.Connection = con
inscmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Could not add User" & ex.Message & " ")
Finally
con.Close()
inscmd.Parameters.Clear()
Success = "User has been added"
End Try
End Sub
End Class
If you could help it would be much appreciated error message is as follows:
Method 'Private Sub btnAdd_Click(ByRef Success As String, sender As Object, e As System.EventArgs)' cannot handle event 'Public Event Click(sender As Object, e As System.EventArgs)' because they do not have a compatible signature. C:\Users\Alwyn\Desktop\Computing A2 Alwyn\Comp4ProjectRoomBookingSystem\WindowsApplication1\WindowsApplication1\FormAdd.vb 10 130 WindowsApplication1
Many thanks in advance.
btnAdd_Click is an event handler, you can't change its predefined signature
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim Success as string
Call AddUser(Success)
MsgBox(" " & Success & " ")
End Sub
remove the Success variable from the declaration and insert as local variable inside the event handler. Of course, if you need that variable also outside the click event, then you need to declare it at form global level
If you want to just send success thru the signature, you can always do an optional call within the signature. (Ex:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs, Optional ByRef Success As String = Nothing ) Handles btnAdd.Click
If Success IsNot Nothing then
Call AddUser(Success)
MsgBox(" " & Success & " ")
End If
End Sub
If you use the optional keyword, and after sender and e, you should have no problems at all with your current way of doing things.
I got the error:
Fill: SelectCommand.Connection property has not been initialized.
I think this is because I declare my data set not inside the private sub but in the public class.....
but I need to use the data set in more than once in different private sub during the program....how should I define it ?
many thanks.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Dim strsql As String
Dim da As New SqlDataAdapter(strsql, con)
Dim ds As New DataSet()
Dim strcon As String
Dim newmode As Boolean
Dim newrow As DataRow
Dim cb As SqlCommandBuilder
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
newmode = False
'Dim con As SqlConnection
'Dim strsql As String
con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;")
strsql = "select*from table_1"
con.Open()
'Dim da As New SqlDataAdapter(strsql, con)
'Dim ds As New DataSet()
da.Fill(ds, "dd")
TextBox1.DataBindings.Add(New Binding("text", ds, "dd.tel"))
TextBox2.DataBindings.Add(New Binding("text", ds, "dd.nam"))
TextBox3.DataBindings.Add(New Binding("text", ds, "dd.address"))
da.update(ds, "dd")
con.Close()
End Sub
Private Sub empty()
textrecord.text = ""
TextBox1.text = ""
TextBox2.text = ""
TextBox3.text = ""
TextBox4.text = ""
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
newrow = ds.Tables("dd").NewRow
newmode = True
textrecord.BackColor = Color.Red
textrecord.Text = "new record"
MsgBox("enter new record and press save")
Call empty()
End Sub
End Class
Instead of:
Dim con As SqlConnection
try adding New:
Dim con As New SqlConnection("initial catalog=test;...")
However, it's best practice to only open a connection just before you need it, and close it right after. Connections should be local variables in Using blocks, not class variables!
You create the DataAdapter at the global level in this line
Dim da As New SqlDataAdapter(strsql, con)
but at this point in time your strsql is empty and if you change it afterwards it doesn't change inside the dataadatpter, thus the error message.
If you insist on keeping all that global vars (and it's considered a bad practice as #Andomar pointed out in is answer) then you should be sure to create the DataAdapter with the correct sqlstring just before its usage:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
newmode = False
con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;")
strsql = "select*from table_1"
con.Open()
da = New SqlDataAdapter(strsql, con) '<- added this line here '
da.Fill(ds, "dd")
....
con.Close()
End Sub