How to Group by Name in Treeview Control - vb.net

I have been googling and searching youtube but find no answer, so I would like to ask for help in here.
I want to group the name in the TreeView control in VB, how can I do it?
Thank you
Public Class FrmPengingat
Private Sub FrmPengingat_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DSLap.PengingatHutang' table. You can move, or remove it, as needed.
Me.PengingatHutangTableAdapter.Fill(Me.DSLap.PengingatHutang)
'fill the tree control
Dim NmPemasok As String
Dim NoNota As String
Dim TglJatuhTempo As Date
Dim Total As Decimal
Dim tmpNmPemasok As String
Dim i As Integer
For i = 0 To DSLap.PengingatHutang.Count - 1
NmPemasok = DSLap.PengingatHutang.Rows(i).Item(0)
tmpNmPemasok = DSLap.PengingatHutang.Rows(i).Item(0)
NoNota = DSLap.PengingatHutang.Rows(i).Item(1)
TglJatuhTempo = DSLap.PengingatHutang.Rows(i).Item(2)
Total = DSLap.PengingatHutang.Rows(i).Item(3)
TreeView1.Nodes.Add(i, NmPemasok).Nodes.Add(i, NoNota & " (" & TglJatuhTempo & ") " & Total)
Next
End Sub
End Class

This line:
TreeView1.Nodes.Add(i, NmPemasok).Nodes.Add(i, NoNota & " (" & TglJatuhTempo & ") " & Total)
adds a new parent node every time. You should check if the tree view already contains a node with the same text and only add a new one if it doesn't.
I suggest you make the key the same as the text for the parent node, that way it'll be easier to check if it exists or not.
Replace the above with this:
If TreeView1.Nodes.ContainsKey(NmPemasok) Then 'The parent node already exists.
TreeView1.Nodes(NmPemasok).Nodes.Add(i, NoNota & " (" & TglJatuhTempo & ") " & Total)
Else 'The parent node doesn't exist.
TreeView1.Nodes.Add(NmPemasok, NmPemasok).Nodes.Add(i, NoNota & " (" & TglJatuhTempo & ") " & Total)
End If

Related

INSERT INTO - errors, but allows input into table

For reasons I cannot see I get the following error message:
Compile error: Method or data member not found
when I use the following:
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Once I click OK and use the refresh button the entry is put into the database, but each time I do an entry I have to go to the same process.
I would like to figure out what method or data is missing?
I should add that there is an outnumber primary key field on this table (Berth_ID), and each time I use the cmd_Add button a new ID number is created for the new record. This includes creating a new ID number for the new record that triggers the error.
Here is all the VBA associated with this form
Private Sub Form_Load()
DoCmd.RunCommand acCmdRecordsGoToLast
End Sub
Private Sub LOCATION_Change()
Me.txt_Cur_Flo = Me.LOCATION.Column(1)
Me.txt_Cur_Doc = Me.LOCATION.Column(2)
Me.txt_Cur_Ori = Me.LOCATION.Column(3)
End Sub
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Private Sub cmd_Clear_Click()
Me.Add_Boat = ""
Me.LOCATION = ""
Me.txt_Cur_Flo = ""
Me.txt_Cur_Doc = ""
Me.txt_Cur_Ori = ""
Me.Add_Boat.SetFocus
End Sub
Private Sub cmd_Close_Click()
DoCmd.Close
End Sub
Consider the best practice of parameterization and not string concatenation of SQL mixed with VBA variables. Due to missing quotes, the compiler attempts to reference a column name and not its literal value. Instead, consider parameterization with defined types which is supported with Access SQL using QueryDefs. Notice below, SQL and VBA are complete separate.
SQL (save as stored query)
PARAMETERS prmBoat TEXT, prmLoc INT, prmBerthed INT;
INSERT INTO BERTHAGE (BOAT, LOCATION, BERTHED)
VALUES(prmBoat, prmLoc, prmBerthed)
VBA
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdef = db.QueryDefs("mySavedParamQuery")
' BIND PARAM VALUES
qdef!prmBoat = Me.Add_Boat
qdef!prmLoc = Me.LOCATION
qdef!prmBerthed = Me.In_Port
' EXECUTE ACTION QUERY
qdef.Execute
Set qdef = Nothing
Set db = Nothing
Even better, save your query with form controls intact and simply call OpenQuery:
SQL (save as stored query)
INSERT INTO BERTHAGE(BOAT, LOCATION, BERTHED)
VALUES(Forms!myForm!Add_Boat, Forms!myForm!LOCATION, Forms!myForm!In_Port)
VBA
Private Sub cmd_Add_Click()
Dim strSQL As String
DoCmd.SetWarnings False ' TURN OFF APPEND PROMPTS
DoCmd.OpenQuery "mySavedActionQuery"
DoCmd.SetWarnings True ' RESET WARNINGS
Call cmd_Clear_Click
End Sub
Missing opening parenthesis after VALUES. Also missing apostrophe in front of Me.Add_Boat. These special characters must always be in pairs, an even number by counting.
If Berth_Week and Berth_Year are number fields (and should be), don't use apostrophe delimiters.
If In_Port is a Yes/No field, don't use apostrophe delimiters.
The issue appears to be that I was doubling up the inputs into the 'week' and 'year' field. this was happening (I believe) because those text box fields were already accessing the week and year information directly from the default value on the BERTHAGE table. Essentially I went through each input and would run it individually waiting for the error to occur. Once it occurred I took it out of the INSERT INFO statement. With the removal of week and year, everything is working. That was a painful exercise, and still not complete, but I am back to a function form/DB so I'll take the small victories when they occur.
Private Sub cmd_Add_Click()
Dim strSQL As String
CurrentDb.Execute " INSERT INTO BERTHAGE " & "(BOAT, LOCATION, BERTHED) VALUES ('" & Me.Add_Boat & "'," _
& Me.New_Loc & "," _
& Me.In_Port & ");"
cmd_Clear_Click
DoCmd.Requery
End Sub`

How to fix this logical error about listbox

I'd like to create a list box in vb.net that lists the item whenever the user clicks the button it updates information, my variables are a string and an integer concatenated, the problem is that when the user clicks on the button the item doesn't remove on the list
I've tried converting the integer variable to string and it still doesn't work
Private Sub btnAddChicken_Click(sender As Object, e As EventArgs) Handles btnAddChicken.Click
If cmbChicken.SelectedIndex = 0 Then
'''qfried is the quantity
'''tfried is the total amount
'''tfried and qfried are the variable i want to update
qfried = qfried + 1
tfried = tfried + pfried
If ListAllOrders.Items.Contains("Fried Chicken - P" & Convert.ToString(tfried) & " Quantity (" & Convert.ToString(qfried) & ")") Then
ListAllOrders.Items.Remove("Fried Chicken - P" & Convert.ToString(tfried) & " Quantity (" & Convert.ToString(qfried) & ")")
ListAllOrders.Items.Add("Fried Chicken - P" & tfried & " Quantity - (" & qfried & ")")
i += 1
Else
ListAllOrders.Items.Add("Fried Chicken - P" & tfried & " Quantity - (" & qfried & ")")
End If
End If
End Sub
I expect that the information would be updated
The remove option of the ListBox does not work with Strings, but with ListBoxItems. For you to remove it, you can do it like this:
For Each item In ListAllOrders.Items
If item.Contains(desiredStringToRemove) Then
ListAllOrders.Items.Remove(item)
Exit for
End If
Next

syntax error in insert into statement on access and vb.net [duplicate]

This question already has answers here:
vb.net escape reserved keywords in sql statement
(2 answers)
Closed 5 years ago.
Im having a error but i dont know what part but i check my tables but it is the exact column im using ms access2010 as database and every time i add a new record theres a msgbox that show (syntax error in insert into statement) heres my code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox1.Enter
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim add As String = "insert into setplan(ma,planqty,side,start,end,total,remarks) values ('" & cmbshift.SelectedItem & "','" & txtplqty.Value & "','" & cmbside.SelectedItem & "','" & timestart.Text & "','" & timeend.Text & "','" & txttotal.Text & "','" & txtrem.Text & "')"
Dim connection As String = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=C:\Users\Administrator\Documents\plan.mdb; Persist Security Info=False;"
Using conn As New OleDb.OleDbConnection(connection)
Try
conn.Open()
If cmbshift.SelectedItem = "" Then
MsgBox("Please Select Shift Schedule")
ElseIf txtplqty.Value = 0 Then
MsgBox("Please Input Plan Quantity")
ElseIf cmbside.SelectedItem = "" Then
MsgBox("Please select Side")
ElseIf timestart.Text = "" Then
MsgBox("Please Select A Start Time")
ElseIf timeend.Text = "" Then
MsgBox("Please Select A Start Time")
ElseIf timeend.Text = timestart.Text Then
MsgBox("Time end must not be equal to Time Start")
Else
MsgBox(add)
Dim cmd As New OleDb.OleDbCommand(add, conn)
cmd.ExecuteNonQuery()
MsgBox("New Schedule Added")
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Sub
Private Sub timestart_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timestart.ValueChanged
End Sub
End Class
start and end words are unique for sql so those keywords might cause the problem. Try to switch those column names into something like startTime and endTime and check if that works.
As has been addressed in the comments, it would be much better if you were to make this a parameterized query instead of concatenating the strings into an explicit SQL command. That being said, however, using your example, there are a couple of things that could be causing the error you describe, some of which have been mentioned in the comments (and the answer from Atilla).
Start and End are reserved keywords in SQL. Using them as column names can cause unexpected behavior when executing a query against those columns from a .NET application through OleDb. There are basically two ways to get around this:
Rename these columns in the database - Atilla suggested StartTime and EndTime, which would probably work nicely.
If renaming the columns is not an option (these columns are used by some other system/process you have in place), your best bet is to modify the query. Since it appears that you're working with an Access database (.mdb) file, you can enclose the column names in your query in square brackets (e.g., [Start] and [End]).
I've actually taken to enclosing all of my table and column names this way when working with Access databases because we have some databases with column names that include spaces and such, so this helps tremendously.
You also need to take into account the actual data types of the columns into which you're attempting to INSERT the data. Again, since it seems that you're using an Access database file, there are a couple of syntactical things to look at.
Values being inserted into a Date/Time field should be wrapped with the # character instead of the ' character.
Numeric field types (e.g., Number or Currency) should not be wrapped with the ' character (or any other characters, for that matter).
If the string values you intend to insert into text fields (e.g., Short Text or Long Text) contain any of a number of "special/invalid characters" including single and/or double quotation marks, these need to be "cleaned up" before executing the query. If this is the case (or potentially could be the case), you could create a method to clean up the string value prior to use in your SQL command. See an example at the bottom of this post in which most, if not all of the potentially invalid characters are simply stripped from the string value.
Please note that, for the purposes of this answer, I've used the data type names from the MS Access UI rather than the actual OleDb/Odbc data types to try to simplify things.
Without knowing the actual data types used in your database table or the values that are coming from the form controls, I can only make assumptions, but, if I absolutely had to use this type of query building (meaning, it's not possible to make it parameterized for some reason), I would probably create the query to looks something more like this:
Dim add As String = "INSERT INTO setplan " & _
"([ma], [planqty], [side], [start], [end], [total], [remarks]) " & _
"VALUES ('" & cmbshift.SelectedItem & "', " & _
txtplqty.Value & ", " & _
"'" & cmbside.SelectedItem & "', " & _
"#" & timestart.Text & "#, " & _
"#" & timeend.Text & "#, " & _
txttotal.Text & ", " & _
"'" & txtrem.Text & "')"
This assumes that the [start] and [end] columns are Date/Time columns, and the [planqty] and [total] columns are some type of Number columns (Integer, Single, etc.).
HOWEVER: as mentioned above, it would be much preferred to make this a parameterized query. Check out the accepted answer to this SO question for more information on how to do this: VB.Net - Inserting data to Access Database using OleDb
Example of cleanup function for String values when concatenating SQL command:
Friend Function CleanStringForSQL(ByVal DirtyString As String) As String
Dim CleanString As String = DirtyString.Replace("'", "")
CleanString = CleanString.Replace("""", "")
CleanString = CleanString.Replace("*", "")
CleanString = CleanString.Replace("\", "")
CleanString = CleanString.Replace("/", "")
CleanString = CleanString.Replace(";", "")
CleanString = CleanString.Replace("%", "")
CleanString = CleanString.Replace("#", "")
CleanString = CleanString.Replace("(", "")
CleanString = CleanString.Replace(")", "")
CleanString = CleanString.Replace("[", "")
CleanString = CleanString.Replace("]", "")
Return CleanString
End Function
Which could then be used in your declaration statement for the SQL command string like:
...
"VALUES ('" & CleanStringForSQL(cmbshift.SelectedItem) & "', " & _
...

VB.NET use variable in textbox name

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()

ExecuteNonQuery() won't work for INSERT function

First of all, I'm not a professional programmer. So there are some big faults possible in my program!
The problem is:
I linked my WPF file in visual express with a MS Access database (format 2003). Whenever I try to run the following (sorry for the dutch code):
Public Sub ToevoegenPersoon(voornaam As String, achternaam As String, mailadres As String, geboortedatum As Date, klantennummer As Integer, specialeCategorie As String)
Dim opdracht As OleDbCommand
Dim sqlOpdracht As String
sqlOpdracht = "INSERT INTO Klant (Voornaam, achternaam, mailadres, geboortedatum, klantennummer, specialeCategorie)" & _
"VALUES (" & Chr(34) & "" & voornaam & "" & Chr(34) & "," & Chr(34) & "" & achternaam & "" & Chr(34) & "," & Chr(34) & "" & _
mailadres & "" & Chr(34) & "," & Convert.ToString(geboortedatum) & "," & Convert.ToString(klantennummer) & "," & Chr(34) & "" & specialeCategorie & "" & Chr(34) & ")"
opdracht = New OleDbCommand(sqlOpdracht, connectie)
Debug.WriteLine(sqlOpdracht)
MsgBox(sqlOpdracht)
opdracht.Connection.Open()
opdracht.ExecuteNonQuery()
opdracht.Connection.Close()
End Sub
my program always has an error for the ExecuteNonQuery() function. This function is used for the following event:
Private Sub btnKlantToevoegen_Click(sender As Object, e As RoutedEventArgs) Handles btnKlantToevoegen.Click
Dim achternaam As String = boxVoornaam.Text
Dim voornaam As String = boxAchternaam.Text
Dim emailadres As String = boxEmailadres.Text
Dim geboortedatum As Date = GeboortedatumSelectie.SelectedDate
Dim klantennummer As Integer = 5
Dim specialeCategorie As String = "Jeugd"
Try
database.ToevoegenPersoon(voornaam, achternaam, emailadres, geboortedatum, klantennummer, specialeCategorie)
Catch ex As Exception
End Try
boxAchternaam.Clear()
boxVoornaam.Clear()
boxEmailadres.Clear()
End Sub
At the top, I stated the following to connect MS Access database with Visual express:
Private connectiestring As String = My.Settings.Database_Drijkoningen_Konings1ConnectionString
Private connectie As OleDbConnection
connectie = New OleDbConnection(connectiestring)
When running this program, the executenonquery() gives an error. And I have no clue whatsoever what it can be. Anybody who does?
Thanks in advance
Jeroen
Not sure if this could resolve your problem. I don't know the error message. However I will show a simple parameterized query that probably could help a lot
Public Sub ToevoegenPersoon(voornaam As String, achternaam As String, mailadres As String, geboortedatum As Date, klantennummer As Integer, specialeCategorie As String)
Dim opdracht As OleDbCommand
Dim sqlOpdracht As String
sqlOpdracht = "INSERT INTO Klant (Voornaam, achternaam, mailadres, " & _
"geboortedatum, klantennummer, specialeCategorie) " & _
"VALUES (?,?,?,?,?,?)"
opdracht = New OleDbCommand(sqlOpdracht, connectie)
opdracht.Parameters.AddWithValue("#p1", voornaam)
opdracht.Parameters.AddWithValue("#p2", achternaam)
opdracht.Parameters.AddWithValue("#p3", mailadres)
opdracht.Parameters.AddWithValue("#p4", Convert.ToString(geboortedatum))
opdracht.Parameters.AddWithValue("#p5", Convert.ToString(klantennummer))
opdracht.Parameters.AddWithValue("#p6", specialeCategorie)
opdracht.Connection.Open()
opdracht.ExecuteNonQuery()
opdracht.Connection.Close()
End Sub
Now, with a parameterized query there is no more concatenations on the command text and this alone will remove any possibility to forget some quote or comma between value. (Of course this removes also the Sql Injection problem and the parsing of strings that contain special characters)
There is still a problem to be resolved. The 4th and 5th parameter receive a string value. This requires the underlying field on the datatable to be a string field and not a DateTime. If this is not the case then you need to pass (as parameter value) just the date value