Visual Basic & SQL Picturebox Controls - arrays

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.

Related

argument out of range parameter name index

since i have the code of the auto generated text box
Insert data from auto generated textbox to SQL Server database
i am try to write a code for ensuring of the auto generated text box in FlowLayoutPanel1 contain data
the auto generated text box build depends on the number in Val(Label2.Text) of the real part
and if any text box is null or empty then the process will stop until fill all fields
the auto generated text box will be like this if the Val(Label2.Text)
is equal to 3
so i try this in the save button
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
so i getting error after leave some text box and back to fill it again
and the all of form code is
Imports System.Data.SqlClient
'library for create folders
Imports System.IO
Public Class part
Dim cLeft As Integer = 1
Dim top1 As Integer = 5
Dim i As Integer = 0
Dim path1 As String
Dim cmd As SqlCommand
Public Sub AddNewTextBox()
Dim txt As New System.Windows.Forms.TextBox()
txt.Top = cLeft * 30
txt.Left = 100
'txt.Text = "TextBox " & Me.cLeft.ToString
cLeft = cLeft + 1
txt.ForeColor = Color.White
txt.BackColor = Color.Gray
txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
txt.Size = New Size(350, 31)
txt.Location = New Point(156, 130 + top1)
txt.TextAlign = HorizontalAlignment.Center
FlowLayoutPanel1.Controls.Add(txt)
End Sub
Private Sub part_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'college part number
Label2.Visible = False
'college path folder
Label3.Visible = False
For m As Integer = 1 To Val(Label2.Text)
AddNewTextBox()
top1 = top1 + 35
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub UpdateUsers()
Using cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Hazim M\Desktop\stud_project\stud_project\Database1.mdf;Integrated Security=True;User Instance=True")
Using cmd As New SqlCommand("INSERT INTO college_part ([name],[coll_of_part],[part_path]) Values (#name,#coll_of_part,#part_path);", cn)
If i < Val(Label2.Text) Then
path1 = Label3.Text & "\" & FlowLayoutPanel1.Controls(i).Text.Trim & Date.Now.Year
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = FlowLayoutPanel1.Controls(i).Text
cmd.Parameters.Add("#coll_of_part", SqlDbType.NVarChar).Value = Label1.Text
cmd.Parameters.Add("#part_path", SqlDbType.NVarChar).Value = path1
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
If Not Directory.Exists(path1) Then
Directory.CreateDirectory(path1)
Else
MsgBox("folder is existing")
End If
End If
End Using
End Using
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
End Class
thank u
I think you need to move dim i Integer=0 to local variable in the Button3_click method. ANd Pass i to the UpdateUser call (add the param to UpdateUser). The current global i keeps adding 1 and eventually out of range.

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

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.

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

Resources