Cant update a record in a database - 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.

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.

Login form cant connect to database

I cannot connect to my database, i receive message "invalid user or password " even if the password is correct, what should i do anyone any idea or my code is wrong here are all my code for login form/
here is my code
Imports System.Data.SqlClient
Public Class LoginForm
Private Sub UsersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UsersBindingNavigatorSaveItem.Click
Me.Validate()
Me.UsersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
End Sub
Private Sub LoginForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DataSet1.users' table. You can move, or remove it, as needed.
Me.UsersTableAdapter.Fill(Me.DataSet1.users)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database_topdent.mdf;Integrated Security=True")
Dim command As New SqlCommand("Select * from users where User = #user and Password = #password ", connection)
command.Parameters.Add("#user", SqlDbType.VarChar).Value = UserTextBox.Text
command.Parameters.Add("#password", SqlDbType.VarChar).Value = PasswordTextBox.Text
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() <= 0 Then
MessageBox.Show("username or textbox invalid")
Else
Form1.Show()
Me.Hide()
End If
End If
End Sub
End Class
This is so confusing.
You need to check for the username and password, not just count the rows. And that table.rows.count "<=0" ? makes no sense to me.
I can see where you were going with it, but its wrong. And the question itself is not clarified enough. But assuming this is a login form. Try this>
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1_Click
Dim connection As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database_topdent.mdf;Integrated Security=True")
Dim command As New SqlCommand("Select * from [users] where [User] = #1 and [Password] = #2 ", connection)
connection.Open()
command.Parameters.AddWithValue("#1", UserTextBox.Text)
command.Parameters.AddWithValue("#2", PasswordTextBox.Text)
Using dr As SqlDataReader = command.ExecuteReader
Dim userFound As Boolean = False
Dim Name As String = ""
While dr.Read
userFound = True
Name = dr("User").ToString
End While
If userFound = True Then
MsgBox("Yes!")
ElseIf userFound = False Then
MsgBox("nay")
End If
End Using
connection.close()
End Sub
Just make sure your columns are set to vchar. I'm not able to test it, but it should work.
First you need to open the connection. Then you need to read the data in your database with the reader. then, if username and password is found, present a msg or whatever you want.
I'm sure there are better ways to do this, but here I am playing a quick good samaritan.
UPDATE #With permissions
1. Add another column named "Permissions"
2. Create a Module.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1_Click
Dim connection As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database_topdent.mdf;Integrated Security=True")
Dim command As New SqlCommand("Select * from [users] where [User] = #1 and [Password] = #2 ", connection)
connection.Open()
command.Parameters.AddWithValue("#1", UserTextBox.Text)
command.Parameters.AddWithValue("#2", PasswordTextBox.Text)
Using dr As SqlDataReader = command.ExecuteReader
Dim userFound As Boolean = False
While dr.Read
userFound = True
User1 = dr("User").ToString
Permissions = dr("Permissions").ToString
End While
If userFound = True Then
MsgBox("Yes!")
ElseIf userFound = False Then
MsgBox("nay")
End If
End Using
connection.close()
End Sub
A module
Module Module1
Public User1 As String
Public Permissions As String
End Module
And then call stuff in your forms...
For example in your main form or wherever, if you have 2 buttons on load form you can do
If Permissions = "admin" then
Button1.enabled = true
else if Permissions = "user" then
msgbox(fu)
end if
Hello here are my code for login with admin/user it works, but know i want to make permission example when user is logged in not have full access , but the admin is full access..
Here are all my codes for ' Login_Form '
Imports System.Data.SqlClient
Module Module1
Public User1 As String
Public Permissions As String
End Module
Public Class LoginForm
Private Sub UsersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles UsersBindingNavigatorSaveItem.Click
Me.Validate()
Me.UsersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DataSet1)
End Sub
Private Sub LoginForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DataSet1.users' table. You can move, or remove it, as needed.
Me.UsersTableAdapter.Fill(Me.DataSet1.users)
If Permissions = "admin" Then
Button1.Enabled = True
ElseIf Permissions = "user" Then
Form1.RaportetToolStripMenuItem.Visible = False
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database_topdent.mdf;Integrated Security=True")
Dim command As New SqlCommand("Select * from [Table_login] where [Username] = #1 and [Password] = #2 ", connection)
connection.Open()
command.Parameters.AddWithValue("#1", UserTextBox.Text)
command.Parameters.AddWithValue("#2", PasswordTextBox.Text)
Using dr As SqlDataReader = command.ExecuteReader
Dim userFound As Boolean = False
Dim Name As String = ""
While dr.Read
userFound = True
Name = dr("Username").ToString
End While
If userFound = True Then
Form1.Show()
ElseIf userFound = False Then
MsgBox("Username or password is wrong!!!!!! ")
End If
End Using
connection.Close()
If Permissions = "user1" Then
Form1.RaportetToolStripMenuItem.Visible = False
End If
End Sub
End Class

Using VB.Net to Insert Data to an Access Database

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

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

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.

Resources