VB.NET use variable in textbox name - vb.net

OK, so I have a form called quote_guidelines and i would like to use a procedure to update my database with values entered into the quote_guidelines form. The values are the descriptions and costs of decorations, food/drink and entertainment. Each tab has been assigned one of these additional servies. I wanted to make a procedure which would update the database with these new values.
The problem was that the query would have to contain a different table and different textbox names. I tried to solve this by saving the names of the tables and textboxes in variables, which will then be passed into the procedure.
the table variable works fine in the sql statement however, the textbox names dont.
I tried this:
quote_guidelines.Controls(description_textbox).Text
But this doesnt work.
Here is my query:
query = "UPDATE " & additional & " SET description='" & quote_guidelines.Controls("" & description_textbox & "").Text & "', cost= " & quote_guidelines.Controls("" & cost_textbox & "").Text & " WHERE " & additional & "ID='" & y & "'"
When I run the program, i get the following error "An unhandled exception of type 'System.NullReferenceException' occurred in EHCC_BookingSystem.exe
Additional information: Object reference not set to an instance of an object."
I just realised that it might be some other stupid mistake i've made so here's the whole procedure:
Sub UpdateAdditionals(textbox3 As System.Object, textbox4 As System.Object, textbox5 As System.Object, textbox6 As System.Object, textbox7 As System.Object, textbox8 As System.Object, ByRef additional As String, ByRef description_textbox As String, ByRef cost_textbox As String)
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "Server=localhost;userid=root;password=root;database=comp4"
Dim reader As MySqlDataReader
MsgBox(additional & description_textbox & cost_textbox)
Try
mysqlconn.Open()
Dim query As String
query = "UPDATE " & additional & " SET description='" & quote_guidelines.Controls.Find(description_textbox, True).FirstOfDefault().Text & "', cost= " & quote_guidelines.Controls.Find(cost_textbox, True).FirstOfDefault().Text & " WHERE " & additional & "ID='" & y & "'"
MsgBox(query)
command = New MySqlCommand(query, mysqlconn)
reader = command.ExecuteReader()
mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub

Try this - Replaced Controls in Controls.Find (Note the `True parameter to search the controls children):
query = "UPDATE " & additional & " SET description='" & TryCast(quote_guidelines.Controls.Find(description_textbox, True)(0), TextBox).Text & "', cost= " & TryCast(quote_guidelines.Controls.Find(cost_textbox, True)(0).Text & " WHERE " & additional & "ID='" & y & "'"
Also note you could do .FirstOfDefault() to get the first control (don't forget to cast):
Controls.Find("nameofcontrol", True).FirstOfDefault()

Related

Update Access database using Visual Studio 2015 - VB.net

I am trying to do a simple update to an Access 2016 database. I am using Visual Studio/VB.net. I have been able to do this already on a different form with no issues using the same type of coding (it's pretty basic, it was for a school project but not anymore). I have tried two different ways to do this...using the update table adapter, for example:
MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
AvailabilityTextBox.Text, EmailTextBox.Text)
Using that method I always get a notImplemented exception thrown even though I have used a similar type of adapter elsewhere. Also I tried using a strung method (I know, not ideal):
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
But this method gives me the error of Syntax Error in UPDATE statement. Again I have used this method elsewhere with no problems. Below I will post all the code for this form.
Imports System.Data
Imports System.Data.Odbc ' Import ODBC class
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class editMediators
Dim NewData As Boolean
Dim objConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ECRDatabase.accdb")
' create functions for save or update
Private Sub runAccessSQL(ByVal sql As String)
Dim cmd As New OleDbCommand
connect() ' open our connection
Try
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Close()
MsgBox("Data Has Been Saved !", vbInformation)
Catch ex As Exception
MsgBox("Error when saving data: " & ex.Message)
End Try
End Sub
Private Sub editMediators_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.MediatorsListTableAdapter.Fill(Me.ECRDatabaseDataSet.mediatorsList) 'loads current mediator information
DateTimePicker1.Value = Today()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'update button
NewData = True
alertMsgBox2()
End Sub
Private Sub alertMsgBox2()
Select Case MsgBox("Yes: Saves Changes," & vbNewLine &
"No: Exits the mediator update window without saving," & vbNewLine &
"Cancel: Returns to the mediator update window.", MsgBoxStyle.YesNoCancel, "Update Mediator Information")
Case MsgBoxResult.Yes
MediatorsListBindingSource.EndEdit()
updateMediator()
'intentionally commented out
'MediatorsListTableAdapter.UpdateMediators(MediatorIDTextBox.Text, MediatorNameTextBox.Text, MaskedTextBox1.Text, MaskedTextBox2.Text, DateTimePicker1.Value,
'AvailabilityTextBox.Text, EmailTextBox.Text)
' Me.Close()
Case MsgBoxResult.No
MediatorsListBindingSource.CancelEdit()
Me.Close()
End Select
End Sub
Private Sub updateMediator()
Dim saveInfo As String
If NewData Then
Dim Message = MsgBox("Are you sure you want to update mediator information? ", vbYesNo + vbInformation, "Information")
If Message = vbNo Then
Exit Sub
End If
Try
'Update mediator information
saveInfo = "UPDATE mediatorsList(mediatorName, email, mediatorPrimaryPhone, mediatorSecondaryPhone, lastMediationDate, availability)
VALUES('" & MediatorNameTextBox.Text & "','" & EmailTextBox.Text & "','" & MaskedTextBox1.Text & "','" & MaskedTextBox2.Text & "',
'" & DateTimePicker1.Value & "','" & AvailabilityTextBox.Text & "', WHERE mediatorID = '" & MediatorIDTextBox.Text & "') "
Catch ex As Exception
End Try
Else
Exit Sub
End If
runAccessSQL(saveInfo)
End Sub
There is obviously something I am missing, though I am not sure it is missing from the code. I checked my database fields and set them to string/text fields just to see if I could get it working. At one time, I had two 2 phone number fields that were set to to the wrong data type so you could only enter a number per int32 requirements. I actually had one of these methods working/updating the db several months ago but I can't figure out what happened since. I do know Visual Studio gave me some problems which probably contributed but it's been too long to remember what happened.
I am rather lost on what else to try as this seems like it should work one way or another. Any ideas what to look at and/or try?? Hopefully I can be pointed in the right direction.
Thanks :)
Your update statement is incorrect, the WHERE clause is inside the VALUES() segment, and should be after it.
Try this instead:
(Edited)
saveInfo = "UPDATE mediatorsList SET mediatorName='" & _
MediatorNameTextBox.Text & "', email='" & EmailTextBox.Text & "', .... WHERE " & _
mediatorID = '" & MediatorIDTextBox.Text & "'"
Also be sure to handle the date correctly. I usually force formatting in yyyy/mmm/dd format.

Insert SQL Query not executed

I am doing the programming on my computer and it works fine-the program, the database itself, inserting to the database is also working fine. But when I publish it and install the program on another computer. It crashes and does not execute the INSERT command.
Here is my code.
Private Sub cmdBlank_Click(sender As System.Object, e As System.EventArgs) Handles cmdBlank.Click
strTariff1 = txtPart1.Text & " " & txtPName1.Text & " " & txtQty1.Text & " " & txtU1.Text
strTariff2 = txtPart2.Text & " " & txtPName2.Text & " " & txtQty2.Text & " " & txtU2.Text
strTariff3 = txtPart3.Text & " " & txtPName3.Text & " " & txtQty3.Text & " " & txtU3.Text
strTariff4 = txtPart4.Text & " " & txtPName4.Text & " " & txtQty4.Text & " " & txtU4.Text
'strTariff5 = txtPart5.Text & " " & txtPName5.Text & " " & txtQty5.Text & " " & txtU5.Text
Call saveToDb()
frmreportax.Show()
End Sub
Private Function saveToDb()
conn.Close()
Dim cmdAdd, cmdCount, cmdAdd2 As New iDB2Command
Dim sqlAdd, sqlCount, sqlAdd2 As String
Dim curr1, curr2, curr3, curr4 As String
Dim count As Integer
conn.ConnectionString = str
conn.Open()
'Check for duplicate entry
sqlCount = "SELECT COUNT(*) AS count FROM cewe WHERE transport=#transport AND blnum=#blnum"
With cmdCount
.CommandText = sqlCount
.Connection = conn
.Parameters.AddWithValue("#transport", frmPart1.txtTransport.Text)
.Parameters.AddWithValue("#blnum", frmPart1.txtNo.Text)
End With
count = Convert.ToInt32(cmdCount.ExecuteScalar())
If count <> 0 Then
MsgBox("Duplicate Entry: " & frmPart1.txtTransport.Text, vbOKOnly + vbExclamation)
Else
sqlAdd = "INSERT INTO cewe (page) " & _
"VALUES (#page) "
With cmdAdd
.Parameters.AddWithValue("#page", Val(frmPart1.txtPage.Text))
.CommandText = sqlAdd
.Connection = conn
.ExecuteNonQuery()
End With
end if
cmdAdd.Dispose()
cmdAdd2.Dispose()
conn.Close()
end function
Please tell me what I am doing wrong? When I run and install the program on my PC, it works perfectly fine. But when I run/install it on another PC, it crashes after the cmdBlank is clicked.
There could be a number of things causing the issue but the first place to look is any error logs or crash report that may give some indication of the problem. Try debugging or logging to get a better picture. Beyond that there are some small suggestions that may help below.
Does the other computer have access to the database you are pointing to? Is the database connection pointing to localhost? In which case you will want to ensure that you have the same credentials (host, username, password, port etc.) set up on the database server on new computer. Are database drivers installed on new computer? What are the fundamental differences between the two machines?
AS400 iSeries DB2 needs to be updated to version 6.xx.0800 and did the tweak!
Installer can be found here
http://www-03.ibm.com/systems/power/software/i/access/windows_sp.html
Problem solved!

SQL Program UPDATE Record Error

I'm working in a small SQL Database program. The programs just there to view, edit and update the database records. Everything is working remarkably well considering I've never tried something like this before. I've managed to get the Add Records, Refresh Records and Delete Records functions working flawlessly. However, I've hit a little bump when trying to UPDATE a selected record.
To clarify, the SQL Table is displayed in a list view, from this list view the end-user can select a particular-record and either edit or delete it.
The edit button opens a new form window with text fields which are automatically filled with the current information of that record.
The code for the edit record form is:
Private Sub frmEdit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
intDB_ID_Selected = CInt(frmMain.lvRec.SelectedItems(0).Text)
Call dispCaption()
Call dispInfo() 'Display the info of the selected ID
End Sub
Private Sub dispInfo()
SQL = "Select * from PersonsA " & _
"where Members_ID=" & intDB_ID_Selected & ""
With comDB
.CommandText = SQL
rdDB = .ExecuteReader
End With
If rdDB.HasRows = True Then
rdDB.Read()
Me.midtxt.Text = rdDB!Members_ID.ToString.Trim
Me.gttxt.Text = rdDB!Gamer_Tag.ToString.Trim
Me.sntxt.Text = rdDB!Screenname.ToString.Trim
Me.fntxt.Text = rdDB!First_Name.ToString.Trim
Me.lntxt.Text = rdDB!Last_Name.ToString.Trim
Me.dobtxt.Text = rdDB!DoB.ToString.Trim
Me.dobtxt.Text = rdDB!DoB.ToString.Trim
Me.emailtxt.Text = rdDB!E_Mail_Address.ToString.Trim
Me.teamptxt.Text = rdDB!Position.ToString.Trim
Me.ugctxt.Text = rdDB!Cautions.ToString.Trim
Me.recordtxt.Text = rdDB!Record.ToString.Trim
Me.eventatxt.Text = rdDB!Event_Attendance.ToString.Trim
Me.Mstattxt.Text = rdDB!Member_Status.ToString.Trim
End If
rdDB.Close()
End Sub
Private Sub dispCaption()
End Sub
Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
Call disControl()
'Validation
If invalidUpdateEntry() = True Then
Call enaControl()
Exit Sub
End If
'Prompt the user if the record will be updated
If MsgBox("Are you sure you want to update the selected record?", CType(MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2 + MsgBoxStyle.Question, MsgBoxStyle), "Update") = MsgBoxResult.Yes Then
'Update query
SQL = "Update PersonsA" & _
"SET Members_ID='" & Me.midtxt.Text.Trim & "'," & _
"Gamer_Tag='" & Me.gttxt.Text.Trim & "'," & _
"Screenname='" & Me.sntxt.Text.Trim & "'," & _
"First_Name='" & Me.fntxt.Text.Trim & "'," & _
"Last_Name='" & Me.lntxt.Text.Trim & "'," & _
"DoB='" & Me.dobtxt.Text.Trim & "'," & _
"E_Mail_Address='" & Me.emailtxt.Text.Trim & "'," & _
"Position='" & Me.teamptxt.Text.Trim & "'," & _
"U_G_Studio='" & Me.ugptxt.Text.Trim & "'," & _
"Cautions='" & Me.ugctxt.Text.Trim & "'," & _
"Record='" & Me.recordtxt.Text.Trim & "'," & _
"Event_Attendance='" & Me.eventatxt.Text.Trim & "'," & _
"Member_Status='" & Me.Mstattxt.Text.Trim & "'" & _
"WHERE Members_ID='" & intDB_ID_Selected & "'"
Call execComDB(SQL) 'Execute the query
Me.Close()
'*** Refresh the list
SQL = "Select * from PersonsA "
Call frmMain.dispRec(SQL)
'--- End of refreshing the list
Exit Sub
Else
Call enaControl()
End If
End Sub
As I've said, I've been able to do everything else using an extremely similar method, but when I try to UPDATE the record I get an error saying
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'Members_ID'.
I know it's this line that's the problem
"WHERE Members_ID='" & intDB_ID_Selected & "'"
Call execComDB(SQL) 'Execute the query
But referencing 'intDB_ID_Selected' has always worked before, and it's been set-up on the update form records load as intDB_ID_Selected = CInt(frmMain.lvRec.SelectedItems(0).Text)
I know this is a huge thread but if anyone could steer me in the right direction WITHOUT telling me to re-write the entire statement I'd be forever grateful.
EDIT1: I fixed the comma before the WHERE clause, but I'm still getting the same error.
Missing a space between
"Update PersonsA " & _
"SET Members_ID= ....
and (as already pointed out) a comma not needed before the WHERE
Said that, do a favor to yourself and to your users. Do not use string concatenation to build a sql command. Use always a parameterized query.
Just as an example
SQL = "Update PersonsA SET Members_ID=#id, Gamer_Tag=#tag, Screenname=#screen," & _
"First_Name=#fname,Last_Name=#lname,DoB=#dob,E_Mail_Address=#email," & _
"Position=#pos,U_G_Studio=#studio,Cautions=#caution,Record=#rec," & _
"Event_Attendance=#event, Member_Status=#stat " & _
"WHERE Members_ID=#id"
SqlCommand cmd = new SqlCommand(SQL, connection)
cmd.Parameters.AddWithValue("#id", Me.midtxt.Text.Trim)
..... so on for the other parameters defined above ....
cmd.ExecuteNonQuery();
Change "Member_Status='" & Me.Mstattxt.Text.Trim & "'," & _
to "Member_Status='" & Me.Mstattxt.Text.Trim & "'" & _
Looks like it was just an extra rogue comma!
On any error like this, use debugging provided with Visual Studio. Inspect the value of SQL, paste into MS SQL Management Studio - it has syntax highlight, and you should be able to spot the error easily.
To prevent further issues (including SQL injection vulnerability), separate this query into an embedded resource, and use parameters. Then it's easy to view, maintain (you can copy/paste between SQL Mgmt Studio and VS), and ultimately use it in code.
A side note, you don't need to use Call in VB.NET, just put a method name with parenthesis.

UPDATE statement failing when attempting to update access database - VB.Net

I am trying to create a simple ticketing software for myself with a VB.Net front end and an Access 2003 back end. I have with allowing new rows to be added, but when I try to code the Update row button, it is giving me the error that says Microsoft JET Database Engine - Syntax error in UPDATE statement. I cannot find what the problem is.
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim ConnectString As String = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\aaron-pister\Desktop\New Role Notes\Issue Tracker Express\Issue Tracker Express\Issue Tracker.mdb")
Dim con As New OleDbConnection(ConnectString)
con.Open()
Dim Green42 As String = "UPDATE Issues Basic Details SET [Company Name] = '" & txtClientName.Text & "', [Status] = '" & cbStatus.Text & "', [Company Contact] = '" & txtClientContact.Text & "', [Description] = '" & txtDesc.Text & "', [Notes] = '" & txtRes.Text & "' WHERE [TicketNum] = '" & txtTicket.Text & "'"
'con.Open()
If txtClientName.Text <> "" Then
Try
'MyCom.CommandText = "UPDATE [Issues Basic Details] SET Company Name = '" & txtClientName.Text & "', Status = '" & cbStatus.Text & "', Company Contact = '" & txtClientContact.Text & "', Description = '" & txtDesc.Text & "', Notes = '" & txtRes.Text & "' WHERE TicketNum = '" & txtTicket.Text & "')"
da = New OleDbDataAdapter(Green42.ToString, ConnectString)
da.Fill(dt)
da.Update(EsInfo1, "Issues Basic Details")
MsgBox("Your record has been updated successfully.", MsgBoxStyle.DefaultButton1, "New Ticket Submitted")
Catch ex As Exception
MsgBox(ex.Source & "-" & ex.Message)
con.Close()
Exit Sub
End Try
Else
MsgBox("You must have an entry in the Client Name, Client Contact and Status fields. It is recommended to also have a value in the Description field.", MsgBoxStyle.OkOnly, "Issue Tracker Express")
btnNewIncident_Click(sender, e)
Exit Sub
End If
End Sub
Your table name has to be bracketed too:
Dim Green42 As String = "UPDATE [Issues Basic Details] SET [Company Name]..."
Also, use parameters instead of putting the values into the string. It avoids SQL Injection.
This:
UPDATE Issues Basic Details SET ...
Is not valid SQL. You need to help it by qualifying your table name:
UPDATE [Issues Basic Details] SET ...
A few other suggestions:
Use prepared statements (parameterize your SQL to avoid SQL injection attacks)
Don't define this type of behavior in a click event handler -- have a helper class to do this work so it can be re-used and isn't coupled directly to the UI.
Use Using statements. Your OleDbConnection class implements IDisposable. You aren't properly disposing this connection.
While it's hard to read your code at the moment, it does look like you are trying to do an "AdHoc" query, which can cause a lot of problems.
I'd recommend first changing your statement to a parameterized query to help diagnose issues too.

NullReferenceException was Unhandled "Object reference not set to an instance of an object."

I have a problem sending data to my access database.
I get this error
NullReferenceExeption was Unhandled - "Object reference not set to an instance of an object."on this part of my codemaxrows = ds.Tables("asdf").Rows.Count
What would that mean?
Here is my code :
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
ID = TextID.Text
FName = Textfname.Text
LName = Textlname.Text
If con.State = ConnectionState.Closed Then
con.Open()
End If
If TextID.Tag & "" = "" Then
cmd = New OleDbCommand("INSERT INTO asdf(ID,fname,lname) " & _
"VALUES(' " & TextID.Text & "', '" & Textfname.Text & "', '" & Textlname.Text & "')", con)
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE asdf" & _
"SET ID=" & TextID.Text & _
", fname='" & Textfname.Text & "'" & _
",lname ='" & Textlname.Text & "'" & _
", WHERE ID =" & TextID.Tag
End If
btnClear.PerformClick()
MessageBox.Show("Data successfully saved!")
maxrows = ds.Tables("asdf").Rows.Count ' <---- Exception occurs here
inc = 1
con.Close()
RefreshData()
End Sub
Put a break-point (F9 or click in the margin) on this line of code: maxrows = ds.Tables("asdf").Rows.Count and run it.
Take these steps:
Hover over ds or right-click and select Quick Watch and see if it
says null.
If it doesn't, highlight ds.Tables("asdf") and Quick Watch it and
see if it's null.
If not, then highlight ds.Tables("asdf").Rows and see if that's
null.
One of these has to be null if it's crashing there. If that's the case, then you didn't fill it correctly or there wasn't nothing to fill it with.