Data not sending to Access database using VB.NET - database

I am having trouble with the following code; it is not sending to the database
I have included all code in case there is a problem elsewhere that is effecting the sending of data to the database
The code is not throwing any errors when running or when btnBook is clicked
Imports System.Data.OleDb
Public Class frmBookRoom
Private DB As New DBControl
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;")
Private Function NotEmpty(text As String) As Boolean
Return Not String.IsNullOrEmpty(text)
End Function
Private Sub AddBooking()
'Add parameters
DB.AddParam("#RoomType", cbxRoomType.Text)
DB.AddParam("#CheckIn", txtCheckIn.Text)
DB.AddParam("#Checkout", txtCheckOut.Text)
DB.AddParam("#NoNights", txtNights.Text)
DB.AddParam("#Adults", txtAdults.Text)
DB.AddParam("#Children", txtChildren.Text)
DB.AddParam("#FullName", txtName.Text)
DB.AddParam("#Revenue", txtPrice.Text)
DB.AddParam("#DateBooked", Date.Today)
'Execute insert command
DB.ExecQuery("INSERT INTO tblRoomBookings([RoomType], [CheckIn], [Checkout], [NoNights], [Adults], [Children], [FullName], [Revenue], [DateBooked])" &
"VALUES(#RoomType, #CheckIn, #Checkout, #NoNiights, #Adults, #Children, #FullName, #Revenue, #DateBooked)")
'Report and abort on errors
If Not String.IsNullOrEmpty(DB.Exception) Then MsgBox(DB.Exception) : Exit Sub
DBCon.Close()
End Sub
Private Sub btnBook_Click(sender As Object, e As EventArgs) Handles btnBook.Click
'Perform the sub routine AddBooking
AddBooking()
'Clear all the text boxes ready for the next entry
cbxRoomType.Text = Nothing
txtCheckIn.Clear()
txtCheckOut.Clear()
txtNights.Clear()
txtAdults.Text = "2"
txtChildren.Text = "0"
txtName.Clear()
txtPrice.Clear()
End Sub
Private Sub frmBookRoom_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Open connection to the database
If DBCon.State = ConnectionState.Closed Then DBCon.Open() : Exit Sub
End Sub
Private Sub frmBookRoom_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'Calendar only displays dates from today forward
MonthCalendar1.MinDate = Date.Today
End Sub
Private Sub btnLessAdults_Click(sender As Object, e As EventArgs) Handles btnLessAdults.Click
'Take one away from the number of adults
txtAdults.Text -= 1
'Don't allow the number to be less than one
If txtAdults.Text <= 1 Then txtAdults.Text = 1
End Sub
Private Sub btnMoreAdults_Click(sender As Object, e As EventArgs) Handles btnMoreAdults.Click
'Add one to the number of adults
txtAdults.Text += 1
End Sub
Private Sub btnLessChildren_Click(sender As Object, e As EventArgs) Handles btnLessChildren.Click
'Take one away from the number of children
txtChildren.Text -= 1
'Don't allow the number of children to be less than zero
If txtChildren.Text <= 0 Then txtChildren.Text = 0
End Sub
Private Sub btnMoreChildren_Click(sender As Object, e As EventArgs) Handles btnMoreChildren.Click
'Add one to the number of children
txtChildren.Text += 1
End Sub
Private Sub btnPrice_Click(sender As Object, e As EventArgs) Handles btnPrice.Click
Dim Nights As Integer
Nights = txtNights.Text
'Calculation to work out the total price of the stay
If cbxRoomType.Text = "single" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£99.99"
Else
txtPrice.Text = "£" & Format(99.99 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "twin" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£124.99"
Else
txtPrice.Text = "£" & Format(124.99 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "double" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£149.99"
Else
txtPrice.Text = "£" & Format(149.99 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "double double" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£164.99"
Else
txtPrice.Text = "£" & Format(164.99 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "mini suite" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£250"
Else
txtPrice.Text = "£" & Format(250 * (1.2 ^ Nights), "0.00")
End If
End If
If cbxRoomType.Text = "master suite" Then
If CDbl("0" + txtNights.Text = 1) Then
txtPrice.Text = "£275"
Else
txtPrice.Text = "£" & Format(275 * (1.2 ^ Nights), "0.00")
End If
End If
btnBook.Enabled = True
End Sub
Private Sub MonthCalendar1_DateSelected(sender As Object, e As DateRangeEventArgs) Handles MonthCalendar1.DateSelected
'Automatically have the first and last date put into the corresponding textboxes
txtCheckIn.Text = MonthCalendar1.SelectionRange.Start.Date.ToString("dd/MM/yyyy")
txtCheckOut.Text = MonthCalendar1.SelectionRange.End.Date.ToString("dd/MM/yyyy")
End Sub
Private Sub cbxRoomType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxRoomType.SelectedIndexChanged, txtCheckIn.TextChanged, txtCheckOut.TextChanged, txtNights.TextChanged, txtName.TextChanged
'Enable buttons for booking and seeingg the price when the length of stay is entered
If Not String.IsNullOrWhiteSpace(txtName.Text) Then
btnPrice.Enabled = True
End If
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
'Clear the form
cbxRoomType.Text = Nothing
txtCheckIn.Clear()
txtCheckOut.Clear()
txtNights.Clear()
txtAdults.Text = "2"
txtChildren.Text = "0"
txtName.Clear()
txtPrice.Clear()
End Sub
Private Sub txtName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtName.KeyPress
'Only allow entry of letters
If Char.IsNumber(e.KeyChar) = True Then
e.Handled = True
ElseIf Char.IsPunctuation(e.KeyChar) = True Then
e.Handled = True
End If
End Sub
Private Sub btnViewEditBookings_Click(sender As Object, e As EventArgs) Handles btnViewEditBookings.Click
'Display View and Edit Bookings form
frmViewEditBookings.Show()
End Sub
Private Sub txtNights_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtNights.KeyPress
'Only allow entry of numbers
If Char.IsLetter(e.KeyChar) = True Then
e.Handled = True
ElseIf Char.IsPunctuation(e.KeyChar) = True Then
e.Handled = True
End If
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
'Close the form
Me.Close()
End Sub
End Class
Thank you for your time :)

Related

Search Functions through Array

I'm super stuck on this one guys and need some help.
I have a multiple arrays Name, age, height, weight which is created on another form where all their data is entered into the arrays but then I need to go to another form where there is text box that I enter one of the name into and click search and then in a text box or list box it will show age, height, weight corresponding to the index of that name search.
My main problem is trying to get the arrays data over to another form and the other problem is trying to get the computer to search through the array know what index it is and show the corresponding data to that index for the other arrays. Been stuck on this for very long now could some please give me suggestions on how to do this it would be heavily appreciated, Thank you.
This is the code/ arrays I have so far
Imports System.IO
Public Class DataEntry
Dim Surname(200)
Dim Firstname(200)
Dim Age(200) As String
Dim HeightA(200) As String
Dim Weight(200)
Dim index As Integer
Public filepath As String = "c:\Patients\All Patients File"
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
Dim di As DirectoryInfo = New DirectoryInfo("c:\Patients")
If di.Exists Then
MsgBox("File is Already There")
txtSur.Enabled = True
txtWeight.Enabled = True
txtHeight.Enabled = True
txtFirst.Enabled = True
txtAge.Enabled = True
btnAddPatient.Enabled = True
btnClear.Enabled = True
btnFileShow.Enabled = True
btnEdit.Enabled = True
btnSave.Enabled = True
txtReader.Enabled = True
Else
di.Create()
MsgBox("File is Already There")
txtSur.Enabled = True
txtWeight.Enabled = True
txtHeight.Enabled = True
txtFirst.Enabled = True
txtAge.Enabled = True
btnAddPatient.Enabled = True
btnClear.Enabled = True
btnFileShow.Enabled = True
btnEdit.Enabled = True
btnSave.Enabled = True
txtReader.Enabled = True
End If
End Sub
Private Sub btnAddPatient_Click(sender As Object, e As EventArgs) Handles btnAddPatient.Click
index = index + 1
lblNum.Text = index
Surname(index) = txtSur.Text
Firstname(index) = txtFirst.Text
Age(index) = txtAge.Text
Weight(index) = txtWeight.Text
HeightA(index) = txtHeight.Text
Dim textAppend As String
textAppend = txtSur.Text & ", " + txtFirst.Text & ", " + txtAge.Text & ", " + txtHeight.Text & "mm" & ", " + txtWeight.Text & "kg" & "."
Try
File.AppendAllText(filepath, textAppend)
MsgBox("Patient Added Successfully")
Catch ex As Exception
MsgBox("Error Adding Patient")
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnFileShow.Click
Dim objreader As New System.IO.StreamReader("c:\Patients\All Patients File")
txtReader.Text = objreader.ReadToEnd
objreader.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
Dim result As Integer = MessageBox.Show("Are You Sure You Want To Clear", "ALERT", MessageBoxButtons.YesNoCancel)
If result = DialogResult.Cancel Then
MessageBox.Show("Cancel pressed")
ElseIf result = DialogResult.No Then
MessageBox.Show("Not Clearing")
ElseIf result = DialogResult.Yes Then
MessageBox.Show("Clearing")
End If
Dim objwriter As New System.IO.StreamWriter("c:\Patients\All Patients File")
'adding text from textbox to text fil
objwriter.Write("")
objwriter.Close()
Array.Clear(Surname, 0, Surname.Length)
Array.Clear(Firstname, 0, Firstname.Length)
Array.Clear(Age, 0, Age.Length)
Array.Clear(Weight, 0, Weight.Length)
Array.Clear(HeightA, 0, HeightA.Length)
index = 0
txtAge.Text = ""
txtFirst.Text = ""
txtHeight.Text = ""
txtSur.Text = ""
txtWeight.Text = ""
txtReader.Text = ""
End Sub
Private Sub DataEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txtSur.Enabled = False
txtWeight.Enabled = False
txtHeight.Enabled = False
txtFirst.Enabled = False
txtAge.Enabled = False
btnAddPatient.Enabled = False
btnClear.Enabled = False
btnFileShow.Enabled = False
btnEdit.Enabled = False
btnSave.Enabled = False
txtReader.Enabled = False
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
If txtReader.Text = "" Then
MsgBox("No Infomation To Edit")
Else
txtReader.Focus()
End If
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If txtReader.Text = "" Then
MsgBox("Nothing To Save")
Else
Dim objwriter As New System.IO.StreamWriter("c:\Patients\All Patients File")
'adding text from textbox to text file
objwriter.Write(txtReader.Text)
objwriter.Close()
MsgBox("Saved Edit")
End If
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Form1.Show()
Me.Hide()
End Sub
End Class
And this is the form I have to get the arrays over to for the search
Public Class SearchPatient
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
End Sub

How to automate changes in stored procedures in SQL Server?

I've got two databases in SQL Server where one database (ConfigDb) references other (DataDb). Many of stored procedures and functions in ConfigDb uses tables and functions/SPs in DataDb. They are referenced like [DataDb].[dbo].[the_object].
Now, I would need to clone the databases to test version, i.e. restore them from backups as ConfigDb_Test and DataDb_Test. Obviously, ConfigDb_Test references DataDb, not the DataDb_Test.
Any tips how to handle this better than opening SP by SP and edit manually?
EDIT
For refernce, I put the utility at GitHub
OK, it is in VB (not c#) -- and I'm not a .net guy, so I'm sure there's a better way to do this.
I caution you to step through and observe the code work, but I use this a lot, and it works great!
Once you enter your servername/credentials, a list of db's will appear (system db's are excluded). Select the db's you want to run against (check list) and enter the find/replace text strings. When you click start, each proc will be opened/scanned, and a REPLACE() is run on matching strings -- so be careful what you put in the FIND/REPLACE text boxes!
Here it goes...
Please, be careful with this, and use at your own risk.
form2.vb
Object Names (in order)
cmbServer (Combo Box)
chkSSPI (Check Box)
txtUser (Text Box)
txtPass (Text Box)
btnConnect (Button)
btnExit (Button)
Code Behind:
Imports System.Data.SqlClient
Public Class Form2
Public objConn As SqlConnection = New SqlConnection()
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cmbServer.SelectedIndex = 0
chkSSPI.Checked = True
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
Private Sub chkSSPI_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkSSPI.CheckedChanged
txtUser.Enabled = Not chkSSPI.Checked
txtPass.Enabled = Not chkSSPI.Checked
txtUser.Select()
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
If chkSSPI.Checked = False Then
objConn.ConnectionString = String.Format("Data Source={0};Initial Catalog=master;User ID={1};Password={2};", cmbServer.Text, txtUser.Text, txtPass.Text)
Else
objConn.ConnectionString = String.Format("Data Source={0}; Initial Catalog=master; Integrated Security=SSPI", cmbServer.Text)
End If
Dim frm2 As Form = New frmDBList()
Try
objConn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Hide()
frm2.Show()
End Sub
Private Sub txtUser_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtUser.TextChanged
End Sub
End Class
frmDBList.vb
Object Names (in order):
clbDatabase (Checked List Box)
txtFind (Text Box)
txtReplace (Text Box)
lblDBName (Label)
lblProcNum (Label) [0]
lblProcCount (Label) [123]
lblProcName (Label)
btnCheckAll (Button)
btnUnCheckAll (Button)
btnStart (Button)
btnClose (Button)
Code Behind:
Imports System.Data.SqlClient
Imports System.IO
Public Class frmDBList
Dim procText As String
Dim procList As New ArrayList
Dim errorLog As New ArrayList
Dim dbcount As Int16
Dim proccount As Int16
Dim replacecount As Int16
Dim procupdate As Boolean
Public Sub LogError(ByVal text As String, ByVal dbname As String, ByVal procname As String)
errorLog.Add("db=" + dbname + " proc=" + procname + " error=" + text)
End Sub
Public Sub SaveLog()
Dim datetime As String = Now.ToString()
datetime = Replace(datetime, "/", "")
datetime = Replace(datetime, ":", "")
Dim filename As String = "c:\procchanger_errorlog " + datetime + ".txt"
Dim objWriter As New System.IO.StreamWriter(filename)
For c As Int16 = 0 To errorLog.Count - 1
objWriter.WriteLine(errorLog(c).ToString())
Next
objWriter.Close()
End Sub
Public Sub AddListBoxItem(ByVal Item As Object, ByVal Check As Boolean)
clbDatabase.Items.Add(Item, Check)
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
btnStart.Enabled = False
btnClose.Enabled = False
errorLog.Clear()
dbcount = 0
proccount = 0
replacecount = 0
grpProgress.Visible = True
If clbDatabase.SelectedItems.Count = 0 Then
MsgBox("Please select at least one database to process.", vbOKOnly)
Else
For i As Integer = 0 To clbDatabase.Items.Count - 1
If clbDatabase.GetItemChecked(i) = True Then
lblDBName.Text = clbDatabase.Items(i).ToString()
dbcount += 1
procList.Clear()
GetProcList(clbDatabase.Items(i).ToString())
End If
Next
MsgBox("Complete. Replaced " + replacecount.ToString() + " occurrences, in " + proccount.ToString() + " stored procedures, across " + dbcount.ToString() + " databases.")
If errorLog.Count > 0 Then
SaveLog()
End If
grpProgress.Visible = False
For i As Integer = 0 To clbDatabase.Items.Count - 1
clbDatabase.SetItemChecked(i, CheckState.Unchecked)
Next
End If
If Form2.objConn.State = ConnectionState.Open Then Form2.objConn.Close()
btnStart.Enabled = True
btnClose.Enabled = True
End Sub
Public Sub GetProcList(ByVal dbname As String)
If Form2.objConn.State = ConnectionState.Closed Then
If Form2.chkSSPI.Checked = False Then
Form2.objConn.ConnectionString = String.Format("Data Source={0};Initial Catalog=" + dbname + ";User ID={1};Password={2};", Form2.cmbServer.Text, Form2.txtUser.Text, Form2.txtPass.Text)
Else
Form2.objConn.ConnectionString = String.Format("Data Source={0}; Initial Catalog=" + dbname + "; Integrated Security=SSPI", Form2.cmbServer.Text)
End If
Try
Form2.objConn.Open()
Catch ex As Exception
LogError(ex.Message, dbname, "")
End Try
End If
Try
Dim sqlcmd = "select name from sysobjects where xtype='P' and name not like 'dt_%'"
Using cmd As New SqlCommand(sqlcmd, Form2.objConn)
Using reader = cmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
procList.Add(reader("name").ToString())
End While
End If
End Using
End Using
Catch ex As Exception
LogError(ex.Message, dbname, "")
End Try
lblProcCount.Text = procList.Count
proccount = procList.Count
For c = 0 To procList.Count - 1
lblProcNum.Text = c.ToString()
lblProcName.Text = procList(c).ToString()
Refresh()
procupdate = False
AlterProc(dbname, procList(c).ToString())
Next
If Form2.objConn.State = ConnectionState.Open Then Form2.objConn.Close()
End Sub
Public Sub AlterProc(ByVal dbname As String, ByVal procname As String)
If Form2.objConn.State = ConnectionState.Closed Then
If Form2.chkSSPI.Checked = False Then
Form2.objConn.ConnectionString = String.Format("Data Source={0};Initial Catalog=" + dbname + ";User ID={1};Password={2};", Form2.cmbServer.Text, Form2.txtUser.Text, Form2.txtPass.Text)
Else
Form2.objConn.ConnectionString = String.Format("Data Source={0}; Initial Catalog=" + dbname + "; Integrated Security=SSPI", Form2.cmbServer.Text)
End If
Try
Form2.objConn.Open()
Catch ex As Exception
LogError(ex.Message, dbname, "")
End Try
End If
Try
Dim sqlcmd = "select * from " + dbname + ".dbo.sysobjects o inner join " + dbname + ".dbo.syscomments c on o.id = c.id where name='" + procname + "'"
Using cmd As New SqlCommand(sqlcmd, Form2.objConn)
procText = ""
Using reader = cmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
procText = procText + reader("text")
End While
End If
End Using
Dim arrProcData() = Split(procText, vbNewLine)
Dim c As Integer
procText = ""
For c = 0 To UBound(arrProcData)
If InStr(UCase(arrProcData(c)), "CREATE") > 0 And InStr(UCase(arrProcData(c)), "PROCEDURE") > 0 Then
arrProcData(c) = Replace(Replace(Replace(arrProcData(c), "CREATE", "ALTER"), "create", "alter"), "Create", "Alter")
End If
If InStr(UCase(arrProcData(c)), UCase(txtFind.Text)) > 0 Then
arrProcData(c) = Replace(UCase(arrProcData(c)), UCase(txtFind.Text), UCase(txtReplace.Text))
replacecount += 1
procupdate = True
End If
procText = procText + arrProcData(c) + vbNewLine
Next
End Using
Catch ex As Exception
LogError(ex.Message, dbname, procname)
End Try
If procupdate = True Then
Try
Dim sqlcmd = procText
Using cmd As New SqlCommand(sqlcmd, Form2.objConn)
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
LogError(ex.Message, dbname, procname)
End Try
End If
End Sub
Private Sub frmDBList_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
grpProgress.Visible = False
Try
Dim sqlcmd = "select name from master.dbo.sysdatabases where name not in ('msdb','master','temdb')"
Using cmd As New SqlCommand(sqlcmd, Form2.objConn)
Using reader = cmd.ExecuteReader()
If reader.HasRows Then
While reader.Read()
AddListBoxItem(reader("name").ToString(), CheckState.Unchecked)
End While
End If
End Using
End Using
Catch ex As Exception
LogError(ex.Message, "master", "")
End Try
Form2.objConn.Close()
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Application.Exit()
End Sub
Private Sub btnCheckAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckAll.Click
For i As Integer = 0 To clbDatabase.Items.Count - 1
clbDatabase.SetItemChecked(i, CheckState.Checked)
Next
End Sub
Private Sub btnUnCheckAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUnCheckAll.Click
For i As Integer = 0 To clbDatabase.Items.Count - 1
clbDatabase.SetItemChecked(i, CheckState.Unchecked)
Next
End Sub
End Class

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

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.

When adding data to the array it says System.IndexOutOfRangeException?

When adding a data to an array I keep getting the error 'System.IndexOutOfRangeException' the Array is declared to bound of 200 and at the data I'm trying to add is at 6 + 1, 6 is the variable count, in the code.
Public Class FormEvents
Dim ArrayEvents(200) As String
Dim Count As Integer
Private Sub FormEvents_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Events As String = "C:\Users\Andrew prince\Desktop\Education\College\Computing\Controlled assesment\Program\Program files\Events.txt"
Dim ObjReader As New StreamReader(Events)
ArrayEvents = ObjReader.ReadLine().Split(",")
UpdateInfo()
ObjReader.Close()
TxtEventNo.Enabled = False
BtnAdd.Enabled = False
End Sub
Sub UpdateInfo()
TxtEventNo.Text = ArrayEvents(Count)
TxtEventType.Text = ArrayEvents(Count + 1)
TxtEventDistance.Text = ArrayEvents(Count + 2)
End Sub
Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles BtnNext.Click
Count = Count + 3
checkInfo()
End Sub
Private Sub BtnPrev_Click(sender As Object, e As EventArgs) Handles BtnPrev.Click
Count = Count - 3
checkInfo()
End Sub
Sub Createvent()
Dim eventNo As String
eventNo = Count / 3
TxtEventNo.Text = eventNo
TxtEventDistance.Text = ""
TxtEventType.Text = ""
BtnNext.Enabled = False
BtnPrev.Enabled = False
BtnAdd.Enabled = True
End Sub
Sub checkInfo()
If Count <= 0 Then Count = 0
If ArrayEvents(Count) = "" Then Createvent() Else UpdateInfo()
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
If TxtEventDistance.Text.Length > 0 And TxtEventType.Text.Length > 0 Then AddToArray()
End Sub
Sub AddToArray()
ArrayEvents(Count) = TxtEventNo.Text
ArrayEvents(Count + 1) = TxtEventType.Text 'error occurs here in the code
ArrayEvents(Count + 2) = TxtEventDistance.Text
Enable()
End Sub
Sub Enable()
BtnAdd.Enabled = False
BtnNext.Enabled = True
BtnPrev.Enabled = True
End Sub
End Class
ArrayEvents is probably no longer 200 in length after you set it in the load method to:
ArrayEvents = ObjReader.ReadLine().Split(",")

Resources