Using VB.Net to Insert Data to an Access Database - 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

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

If statement to not allow insert statement to work because a cell is null

I want the code to not allow the complete button to work because the column of "StartTime" is null.
Attached is the code below:
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Public Class Etask
Dim con As SqlConnection
Dim cmd As SqlCommand
Private Sub Etask_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Labelname.Text = login.mname
Dim str As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
Dim con As New SqlConnection(str)
Dim com As String = "SELECT TaskID, Name, TaskAssigned, StartTime, FinishTime, Status
FROM dbo.Tasks
WHERE Name = '" & Labelname.Text & "'"
Dim Adpt As New SqlDataAdapter(com, con)
Dim ds As New DataSet()
Adpt.Fill(ds, "PosTable")
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub Etask_Resize(sender As Object, e As EventArgs) Handles Me.Resize
Panel1.Left = (Me.Width - Panel1.Width) / 2
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
refreshDGV()
End Sub
Public Sub refreshDGV()
Labelname.Text = login.mname
Dim str As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
Dim con As New SqlConnection(str)
Dim com As String = "SELECT TaskID, Name, TaskAssigned, StartTime, FinishTime, Status
FROM dbo.Tasks
WHERE Name = '" & Labelname.Text & "'"
Dim Adpt As New SqlDataAdapter(com, con)
Dim ds As New DataSet()
Adpt.Fill(ds, "PosTable")
DataGridView1.DataSource = ds.Tables(0)
End Sub
'complete button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection("Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true")
Dim query As String = "update Tasks set FinishTime=#FinishTime,Status=#Status where TaskID=#id"
con.Open()
cmd = New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#FinishTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = comboboxstatus.Text
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Successfully updated!")
refreshDGV()
End Sub
Private Sub FillByToolStripButton_Click(sender As Object, e As EventArgs)
Try
Me.TasksTableAdapter.FillBy(Me.RestaurantDatabaseDataSet2.Tasks)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Me.LabelID.Text = DataGridView1.Item(0, i).Value
End Sub
Private Sub btnstart_Click(sender As Object, e As EventArgs) Handles btnstart.Click
Dim con As New SqlConnection("Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true")
Dim query As String = "update Tasks set StartTime=#StartTime,Status=#Status where TaskID=#id"
con.Open()
cmd = New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#StartTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = "Working on it!"
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Successfully started!")
refreshDGV()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = Date.Now.ToString("dd MMM yyyy hh:mm:ss")
End Sub
End Class
This is what the application looks like:
I want the code to check for null data in the StartTime column. If its null, then the complete button won't work. Button1 is the button to complete a task.
ExecuteNonQuery returns an integer with the number of rows affected.
If you create the query so that it does not do an update if the column is NULL, then it will return 0, which you can check for.
Also, it is easier to put the connection string in just one place, so that if you need to change it you only have to do so once - it is too easy to miss an occurrence of the string and have to go and edit it again. Often, such data is stored in the settings for the program, but I've made it as a constant for this example:
Public Const CONNSTR As String = "Data Source=ICECANDY;Initial Catalog=RestaurantDatabase;integrated security=true"
'....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query As String = "UPDATE Tasks
SET FinishTime = #FinishTime, Status = #Status
WHERE TaskID = #id
AND StartTime IS NOT NULL"
Dim nRowsAffected = 0
Using con As New SqlConnection(CONNSTR),
cmd As New SqlCommand(query, con)
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = LabelID.Text
cmd.Parameters.Add("#FinishTime", SqlDbType.VarChar).Value = Label1.Text
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = comboboxstatus.Text
con.Open()
nRowsAffected = cmd.ExecuteNonQuery()
End Using
If nRowsAffected = 0 Then
MsgBox("Database not updated - check for empty StartTime.")
Else
MsgBox("Successfully updated!")
End If
refreshDGV()
End Sub
The Using statement makes sure that "unmanaged resources" are released when it is done.

Playing multiple audio files using system() in C

I've written a C code to play 3 audio files one after other using vlc but the after playing first file it's not proceeding I've to press Ctrl+C or q to go to next song which I want to happen itself.
I placed system("q") after every file so that it may fulfill my task but it's still not working.
#include<stdio.h>
int main(){
system("vlc 1.mp3");
system("q");
system("vlc 2.mp3");
system("q");
system("vlc 3.mp3");
system("q");
return 0;
}
I think you should use mplayer in slave mode instead of vlc. It is more flexible and has more control. you can send command to mplayer as you wish. please study the following link
http://www.mplayerhq.hu/DOCS/tech/slave.txt
I suggest you to use python for linux and C# or VB.NET for windows. I can supply some vb.net code if you need it.
This was my old answer for another question.
but I will post here for you too.
I am developing android phone remote control + VB.NET TCP server - mplayer. I am using mplayer in slave mode. I send command from android app to VB.NET TCP server. Then the command will send to mplayer.
I will show some code that control and send the mplayer desired commands, but the server part is not finished yet. The coding is no finished yet but I hope it is useful for you.
Imports System.ComponentModel
Imports System.IO
Imports System.Data.OleDb
Public Class Form1
Private bw As BackgroundWorker = New BackgroundWorker
Dim i As Integer = 0
Dim dbFile As String = Application.StartupPath & "\Data\Songs.accdb"
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & dbFile & "; persist security info=false"
Public conn As New OleDbConnection(connstring)
Dim sw As Stopwatch
Dim ps As Process = Nothing
Dim jpgPs As Process = Nothing
Dim args As String = Nothing
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
If bw.CancellationPending = True Then
e.Cancel = True
Exit Sub
Else
' Perform a time consuming operation and report progress.
'System.Threading.Thread.Sleep(500)
bw.ReportProgress(i * 10)
Dim dir_info As New DirectoryInfo(TextBox1.Text)
ListFiels("SongList", TextBox2.Text, dir_info)
End If
End Sub
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
If e.Cancelled = True Then
Me.tbProgress.Text = "Canceled!"
ElseIf e.Error IsNot Nothing Then
Me.tbProgress.Text = "Error: " & e.Error.Message
Else
Me.tbProgress.Text = "Done!"
End If
End Sub
Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
Me.tbProgress.Text = e.ProgressPercentage.ToString() & "%"
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Try
ps.Kill()
Catch
Debug.Write("already closed")
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False 'To avoid error from backgroundworker
bw.WorkerReportsProgress = True
bw.WorkerSupportsCancellation = True
AddHandler bw.DoWork, AddressOf bw_DoWork
AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
funPlayMusic()
End Sub
Private Sub buttonStart_Click(sender As Object, e As EventArgs) Handles buttonStart.Click
If Not bw.IsBusy = True Then
bw.RunWorkerAsync()
End If
End Sub
Private Sub buttonCancel_Click(sender As Object, e As EventArgs) Handles buttonCancel.Click
If bw.WorkerSupportsCancellation = True Then
bw.CancelAsync()
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If Not bw.IsBusy = True Then
sw = Stopwatch.StartNew()
bw.RunWorkerAsync()
sw.Stop()
Label1.Text = ": " + sw.Elapsed.TotalMilliseconds.ToString() + " ms"
End If
End Sub
Private Sub ListFiels(ByVal tblName As String, ByVal pattern As String, ByVal dir_info As DirectoryInfo)
i = 0
Dim fs_infos() As FileInfo = Nothing
Try
fs_infos = dir_info.GetFiles(pattern)
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
For Each fs_info As FileInfo In fs_infos
i += 1
Label1.Text = i
insertData(tblName, fs_info.FullName)
lstResults.Items.Add(i.ToString() + ":" + fs_info.FullName.ToString())
If i = 1 Then
Playsong(fs_info.FullName.ToString())
Else
i = 0
lstResults.Items.Clear()
End If
Next fs_info
sw.Stop()
Label1.Text = ": " + sw.Elapsed.TotalMilliseconds.ToString() + " ms"
fs_infos = Nothing
Dim subdirs() As DirectoryInfo = dir_info.GetDirectories()
For Each subdir As DirectoryInfo In subdirs
ListFiels(tblName, pattern, subdir)
Next
End Sub
Private Sub insertData(ByVal tableName As String, ByVal foundfile As String)
Try
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
Dim SqlQuery As String = "INSERT INTO " & tableName & " (SngPath) VALUES (#sng)"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandType = CommandType.Text
.CommandText = SqlQuery
.Connection = conn
.Parameters.AddWithValue("#sng", foundfile)
.ExecuteNonQuery()
End With
conn.Close()
Catch ex As Exception
conn.Close()
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnClearList_Click(sender As Object, e As EventArgs) Handles btnClearList.Click
lstResults.Items.Clear()
End Sub
Private Sub funPlayMusic()
ps = New Process()
ps.StartInfo.FileName = "D:\Music\mplayer.exe "
ps.StartInfo.UseShellExecute = False
ps.StartInfo.RedirectStandardInput = True
jpgPs = New Process()
jpgPs.StartInfo.FileName = "D:\Music\playjpg.bat"
jpgPs.StartInfo.UseShellExecute = False
jpgPs.StartInfo.RedirectStandardInput = True
'ps.StartInfo.CreateNoWindow = True
args = "-fs -noquiet -identify -slave " '
args += "-nomouseinput -sub-fuzziness 1 "
args += " -vo direct3d, -ao dsound "
' -wid will tell MPlayer to show output inisde our panel
' args += " -vo direct3d, -ao dsound -wid ";
' int id = (int)panel1.Handle;
' args += id;
End Sub
Public Function SendCommand(ByVal cmd As String) As Boolean
Try
If ps IsNot Nothing AndAlso ps.HasExited = False Then
ps.StandardInput.Write(cmd + vbLf)
'MessageBox.Show(ps.StandardOutput.ReadToEndAsync.ToString())
Return True
Else
Return False
End If
Catch ex As Exception
Return False
End Try
End Function
Public Sub Playsong(ByVal Songfilelocation As String)
Try
ps.Kill()
Catch
End Try
Try
ps.StartInfo.Arguments = args + " """ + Songfilelocation + """"
ps.Start()
SendCommand("set_property volume " + "80")
Catch e As Exception
MessageBox.Show(e.Message)
End Try
End Sub
Private Sub lstResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstResults.SelectedIndexChanged
Playsong(lstResults.SelectedItem.ToString())
End Sub
Private Sub btnPlayJPG_Click(sender As Object, e As EventArgs) Handles btnPlayJPG.Click
Try
' jpgPs.Kill()
Catch
End Try
Try
'ps.StartInfo.Arguments = "–fs –mf fps=5 mf://d:/music/g1/Image00020.jpg –loop 200" '-vo gl_nosw
'jpgPs.Start()
Shell("d:\Music\playjpg.bat")
' SendCommand("set_property volume " + "80")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub btnPlayPause_Click(sender As Object, e As EventArgs) Handles btnPlayPause.Click
SendCommand("pause")
End Sub
Private Sub btnMute_Click(sender As Object, e As EventArgs) Handles btnMute.Click
SendCommand("mute")
End Sub
Private Sub btnKaraoke_Click(sender As Object, e As EventArgs) Handles btnKaraoke.Click
'SendCommand("panscan 0-0 | 1-1")
SendCommand("af_add pan=2:1:1:0:0")
End Sub
Private Sub btnStereo_Click(sender As Object, e As EventArgs) Handles btnStereo.Click
SendCommand("af_add pan=2:0:0:1:1")
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
Playsong("d:\music\iot.mp4")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'SendCommand("loadfile d:\music\iot.mp4")
'SendCommand("pt_step 1")
End Sub
End Class

Database update will not work

I know that you guys will find this simple, but can anyone tell me why I am getting a syntax error despite following every instruction on numerous sites?
My code in full is:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = F:\Brett\Programming Projects\Roster\Roster.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
' This is grabbing all the records from the listing table in the Roster Database
sql = "Select * FROM Listing"
' Or selected columns
'sql = "SELECT Listing.FName, Listing.LName FROM Listing"
da = New OleDb.OleDbDataAdapter(sql, con)
' Populate the dataset with the data adaptor. This can be any name
da.Fill(ds, "Roster")
con.Close()
MaxRows = ds.Tables("Roster").Rows.Count
inc = -1
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim iRow As Integer = Me.Label1.Text
Dim junk As Integer
ds.Tables("Roster").Rows(iRow).Item(5) = Me.TextBox3.Text
ds.Tables("Roster").Rows(iRow).Item(6) = Me.TextBox4.Text
ds.Tables("Roster").Rows(iRow).Item(8) = Me.TextBox5.Text
da.Update(ds, "Roster")
'da.Update(ds)
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim newtbl As DataTable
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim cmd As New OleDb.OleDbCommand
newtbl = ds.Tables("Roster")
Dim drCurrent As DataRow
drCurrent = newtbl.NewRow()
drCurrent(1) = "sfd"
drCurrent(2) = "werter"
newtbl.Rows.Add(drCurrent)
da.Update(ds, "Roster")
End Sub
No matter what I do, I get this error message. Any help will be greatly appreciated as this is two days now...
I would show you my error but as usual, some peanut won't let me without some crap.. It states OleDbException was unhandled, Syntax error in Insert Into statement.
Can you try wrapping your database calls in a try-catch block and inspect the InnerXml that's returned with the exception?
That might give you more information about the error that you're getting.

How to declare a connection object on a class level connection not in local scope with VB.NET?

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

Resources