Loopings in VB.net with two text boxes - vb.net

I have two text boxes in a user-input form asking for a VisitID(s) and to set a price.
It then uses the following code to update each VisitID with a single price.
myCmd1.CommandText = "UPDATE tblVisit SET Price = (" & CustomerRefString & ") WHERE VisitID IN (" & VisitIDString & ")"
I understand that the above code loops for each VisitID in the VisitIDString, but how do I loop to allow updating each visitID with the corresponding line in the Price TextBox?
Private Sub btnOk_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim VisitIDString AS String
Dim VisitIDsUpdated As Object
Dim myComma() As Char = {","}
Dim connString As String
Dim DataSourceBase = Report.GetDataSource("Connection")
Dim ConnectionCollection = Report.Dictionary.Connections
connString = ConnectionCollection(0).ConnectionString
VisitIDString = VisitIDTextBox.Text
VisitIDString = VisitIDString.Replace(vbCr, "").Replace(vbLf, ",")
VisitIDString = VisitIDString.Replace(" ", "")
VisitIDString = VisitIDString.TrimEnd(MyComma)
Report.SetParameterValue("VisitIDByte",VisitIDString)
'------------------------------------------------------------------------------------------------------------
Dim CustomerRefString AS String
Dim CusterRefUpdated As Object
Dim myCommaRef() As Char = {","}
'------------------------------------------------------------------------------------------------------------
CustomerRefString = CustomerRefTextBox.Text
CustomerRefString = CustomerRefString.Replace(vbCr, "").Replace(vbLf, ",")
CustomerRefString = CustomerRefString.Replace(" ", "")
CustomerRefString = CustomerRefString.TrimEnd(MyComma)
'------------------------------------------------------------------------------------------------------------
myConn = New SqlConnection(connString) 'after changes
'Create a Command object
myCmd1 = myConn.CreateCommand
myCmd1.CommandText = "UPDATE tblVisit SET Price = (" & CustomerRefString & ") WHERE VisitID IN (" & VisitIDString & ")"
'Open the connection.
myConn.Open()
'Execute the statement and return a single value. If you wanted to return more than 1 value you need to add a loop here.
VisitIDsUpdated = myCmd1.ExecuteScalar()
'Close the database connection.
myConn.Close()
End Sub

There are better ways to create your user interface, but if you have to do it this way (with textboxes), then you can solve the problem easily as long as the user enters the data correctly.
Assuming you have "id" and "price" data that looks something like this:
---------
|ID|PRICE|
---------
|11|1.11 |
|22|2.22 |
|33|3.33 |
---------
The user would paste these values into the VisitIDTextBox textbox:
11
22
33
And the user would paste these values into the Price textbox:
1.11
2.22
3.33
Then your solution relies on the fact that the index number of the item in the VisitIDTextBox textbox would match the index number of the item in the Price textbox.
So you would convert the contents of both textboxes into an array. Below is a simple example of you can do that for the VisitIDTextBox textbox.
'Any character in this array will be used to split the string
Dim sAAA As String = ",|" & vbCrLf
Dim arSplitOnValues() As Char = sAAA.ToCharArray()
'Create an array of visit ID's
Dim arVisitIDs() As String = VisitIDTextBox.Text.Split(arSplitOnValues, System.StringSplitOptions.RemoveEmptyEntries)
After doing the same for the values in the Price textbox, you would now have two arrays; arVisitIDs and arPrices
The index of each item in the arrays would now match up, so you can select from arVisitIDs and arPrices using the same index and get the price that matches the ID.
You can see this by using a simple loop like this:
For iLpr As Integer = 0 To arVisitIDs.GetUpperBound(0)
MessageBox.Show(Me, arVisitIDs(iLpr) & "~" & arPrices(iLpr), "Test", MessageBoxButtons.OK, MessageBoxIcon.Information)
Next iLpr
When run, you'll get three messageboxes with values like this:
11~1.11
22~2.22
33~3.33

Related

MS Access capture certain group of text, append, and loop onto next section in a long text field

I have a long text field (called "reporttext") that someone is importing a bunch of text that needs to be separated and appended into another table. For each case, there's a "[]" character that is supposed to separate each case. I want my code to look for the first [] and second [], append the text to another table and then loop. So the next case would be the text between the second [] and third [].
Here's my string
Reporttext: [] ksfjjls [] 42244 [] ####
I would want this to append to a new table called "notes" where it would be like this:
Reporttext
ksfjjls
42244
####
I used a macro to count the number of [] in the text file to know how many times to run the loop, but this, along with the rest of my code just isn't happening. I know my code is wrong, but I know with a few tweaks it'll get there. Any help is appreciated.
lengthofnote = Len([reporttext])
start = InStr([reporttext], "[]")
startplus3 = [start] + 3
'find number of cases
firstcase = 1
numcases = StringCountOccurrences([reporttext], "[]")
Dim LCounter As Integer
For LCounter = [firstcase] To [numcases]
revisedreporttext = Mid([reporttext], [startplus3], [lengthofnote])
secondposition = InStr([revisedreporttext], "[]")
nextreporttext = Mid([reporttext], [startplus3], [secondposition])
Add_reporttext = "INSERT INTO notes(reporttext) values ('" & nextreporttext & "');"
DoCmd.RunSQL Add_reporttext
firstcase = firstcase + 1
startplus3 = secondposition
secondposition = secondposition + 4
Next LCounter
#Zev Spitz is correct in that you could use Split() to accomplish this. You could use something like this
Option Compare Database
Option Explicit
Sub SplitLongTextField()
Dim rs As Recordset
Dim reportTextArr
Dim qString As String
Dim i As Long
qString = "SELECT [reporttext] FROM [Table1]" '<- replace [Table1] with the name of your table with the Long Text field
Set rs = CurrentDb.OpenRecordset(qString)
If Not rs.EOF Then
reportTextArr = Split(rs.Fields("reporttext"), "[]")
End If
For i = LBound(reportTextArr) To UBound(reportTextArr)
If Not reportTextArr(i) = "" Then
DoCmd.RunSQL "INSERT INTO notes(reporttext) VALUES('" & reportTextArr(i) & "');"
End If
Next i
rs.Close
End Sub
If you needed to do this for multiple records from your initial table then you could loop through the entire table and loop the operation like
Option Compare Database
Option Explicit
Sub SplitLongTextField()
Dim rs As Recordset
Dim reportTextArr
Dim qString As String
Dim i As Long
qString = "SELECT [reporttext] FROM [Table1]" '<- replace [Table1] with the name of your table with the Long Text field
Set rs = CurrentDb.OpenRecordset(qString)
Do Until rs.EOF
reportTextArr = Split(rs.Fields("reporttext"), "[]")
For i = LBound(reportTextArr) To UBound(reportTextArr)
If Not reportTextArr(i) = "" Then
DoCmd.RunSQL "INSERT INTO notes(reporttext) VALUES('" & reportTextArr(i) & "');"
End If
Next i
rs.MoveNext
Loop
rs.Close
End Sub
Assuming the string always starts with [] and preference is to return a single string, consider:
Replace(Mid(reporttext, 4), "[] ", vbCrLf)

Update datatable and show new value

I am trying to update datatable and print out updated row but I am getting an old value. Here is my code:
Public Shared zadnjiBrojevi As DataTable
...
aaaa.ItemsSource = Globals.zadnjiBrojevi
Dim lastnr As Integer
Dim result() As DataRow = Globals.zadnjiBrojevi.Select("tip = " & tipoviDokumenataCbox.SelectedItem.tag & "")
For Each row As DataRow In result
lastnr = row(1)
Next
Console.WriteLine("Last number is: " & lastnr)
Dim myRow() As Data.DataRow
myRow = Globals.zadnjiBrojevi.Select("tip = '" & tipoviDokumenataCbox.SelectedItem.tag & "'")
myRow(0)("lastnr") = myRow(0)("lastnr") + 1
Dim filename As String = Globals.rootPath & "ZadnjiBrojevi.xml"
Globals.zadnjiBrojevi.WriteXml(filename, XmlWriteMode.WriteSchema)
Console.WriteLine("Dodan upis!")
In console i am always getting "Last number is: 4443". But GridControl "aaaa" shows updated values. And "writexml" writes updated values.

Loop, aggregate and return unique DataRow sum

I have a DataGrid which contains multiple transactions of Customer's buy ins.
What I want is to add up the transaction buy ins from each customer and add the result on the related images. What I have at the moment gives me logic errors i.e. adding the same amounts on more than one images.
Here is the structure of my DataGrid (column titles): [Name,Surname, Buyin, Type, StartTime, TransactionID, CustomerID]
and here is my code:
Dim tbActivePlayers As DataTable = Me.ActivePlayersTableAdapter.GetData()
Dim tbTemp As New DataTable
' table = DataSet.Tables("Orders")
' Declare an object variable.
Dim objTotalBuyin As Object
Dim iCount, ilbl As Integer
ilbl = 1
Dim viewUniquePlayers As New DataView(tbActivePlayers)
Dim iActivePlayers As Integer = viewUniquePlayers.ToTable(True, "CustomerID").Rows.Count
Dim dtDataTable As DataTable = viewUniquePlayers.ToTable(True, "CustomerID")
Dim myLabel As Label
For iCount = 0 To dtDataTable.Rows.Count
objTotalBuyin = tbActivePlayers.Compute("Sum(Buyin)", "CustomerID = " & tbActivePlayers.Rows(iCount).Item("CustomerID"))
'MsgBox("Name: " & tbActivePlayers.Rows(iCount + 1).Item("Name") & ", Sumbuyin:" & sumObject.ToString & " ResultCount:" & ResultCount)
'
myLabel = CType(Me.Controls.Find("lblPlayer" & ilbl, True)(0), Label)
If Not myLabel Is Nothing Then
myLabel.Text = "Empty Seat"
End If
'
myLabel.Text = tbActivePlayers.Rows(iCount).Item("Name") & Environment.NewLine & _
"€" & objTotalBuyin.ToString
myLabel.Image = Global.PokerBusiness.My.Resources.Resources.seatocc
ilbl += 1
Next
Your filter function for the Compute seems to be based off each row in tbActivePlayers, yet you're looping over each row (and thus counting the rows of) a view of unique players. My brain compiler tells me this might well be the source of your logic errors, because you're potentially computing your sum with a filter that's using a single, unique customer ID more than once. Consider changing
objTotalBuyin = tbActivePlayers.Compute("Sum(Buyin)", "CustomerID = " & tbActivePlayers.Rows(iCount).Item("CustomerID"))
To
objTotalBuyin = tbActivePlayers.Compute("Sum(Buyin)", "CustomerID = " & dtDataTable.Rows(iCount).Item("CustomerID"))

Filter Data from dataset that is passed to textbox

I am iterating through columns in a datagridview in vb net and passing the
values to a textbox. I need to be able to filter out the emails which are in Cell(4), so that there are no duplicate emails for any single customer.
I have no idea of how to do this using a dataset.
EmailTableAdapter.Fill(Me.EmailDataset.Email)
Dim r As String = String.Empty
For i As Integer = 0 To Me.EmailDataGridView.RowCount - 1
r = r & EmailDataGridView.Rows(i).Cells(7).Value.ToString & " - " & EmailDataGridView.Rows(i).Cells(4).Value.ToString & vbNewLine
Next
TextBox2.Text = (r)
One way to filter out rows with duplicate values in Cells(4) would be to iterate through the grid rows, stuffing items into a Dictionary using Cells(4) values as the Key, and then iterate through the Dictionary to build your "r" string. Such a solution would look something like this:
EmailTableAdapter.Fill(Me.EmailDataset.Email)
Dim EmailDict As New Dictionary(Of String, String)
For i As Integer = 0 To Me.EmailDataGridView.RowCount - 1
If Not EmailDict.ContainsKey(EmailDataGridView.Rows(i).Cells(4).Value.ToString) Then
EmailDict.Add(EmailDataGridView.Rows(i).Cells(4).Value.ToString, EmailDataGridView.Rows(i).Cells(7).Value.ToString)
End If
Next
Dim EmailPair As KeyValuePair(Of String, String)
Dim r As String = String.Empty
For Each EmailPair In EmailDict
r &= EmailPair.Value & " - " & EmailPair.Key & vbNewLine
Next
TextBox2.Text = (r)

for loop for a string variable

this is my code -
for i as integer = 0 to rows.count - 1
output &= "Name =" & row(i)("Name")
output &= "lastName =" & row(i)("lastName")
... 50 more fields
next
i need the output to be like this
Applicant1Name = MikeApplicant1lastName = ditkaApplicant2Name = TomApplicant2lastName = Brady ...
how do i do this without putting the following code 50 times -
output &= "Applicant" & i.tostring() + 1 &"Name =" & row(i)("Name")
... and so on.
is there a way to make a for loop and run applicant 1,2,3,4.... in one shot?
thanks
Try:
Dim output as New StringBuilder("")
For i as Integer = 0 To rows.Count - 1
output.append("Applicant" + i.ToString())
Foreach(col as DataColumn in dt.Columns) ' The datatable where your rows are
Dim colName as string = col.ColumnName
output.append(colName & "=" & rows(i)(colName).ToString())
Next
If i < rows.Count - 1 Then output.Append("|")
Next
StringBuilder is faster for string concatenations, and if you keep your rows in a datatable (which I assume is happening because that's how it looks like you're accessing them), then you can just iterate through the columnnames at the top level.
You really cant as you are trying to append 50 different fields.
The only thing you can shorten is the variable name:
Dim strLN as String = row(i)("lastName")
Dim strFirstName as String = row(i)("firstName")
Then you simply put it all together
output &= strLN & strFirstName...etc
looks like you want to create an array of all the fields you have and then include a nested loop.
Dim fields As String() = {"Name", "LastName", "SSN", "Birthdate"}
Dim output As String = ""
For i As Integer = 1 To rows.count
For Each field As String In fields
output = String.Concat(output, "Applicant ", i, field, "=", row(i)(field), " ")
Next
Next