for loop for a string variable - vb.net

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

Related

Loopings in VB.net with two text boxes

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

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)

VB.net Updating Datatable error Index was outside the bounds of the array

I am trying to update the "qnty" column of a specific row in ds.Tables(0) but I don't know why this problem appear even though "qnty" in ds.Table(0) exist?
"Index was outside the bounds of the array."
I use VS 2012, VB.NET
Dim Minus_qnty As String
Dim Row() As Data.DataRow
Row = ds.Tables(0).Select("Prodno = '" & ProdItem_No & "'")
Dim ds_qnty As String = ds.Tables(0).Rows(0)("qnty").ToString()
Minus_qnty = ds_qnty + Prod_taken_qnty
Row(0)("qnty") = Minus_qnty 'The problem appear in this line
Change your last line to check for row length
If Row.Length > 0 Then Row(0)("qnty") = Minus_qnty
The error is because there are no records in the DataTable matching your condition Prodno = ProdItem_No.
I think this is what you wanted to do:
Dim Minus_qnty As String
Dim Row() As Data.DataRow
Row = ds.Tables(0).Select("Prodno = '" & ProdItem_No & "'")
If Row.Length > 0 Then
Dim ds_qnty As String = Row(0)("qnty").ToString()
Minus_qnty = ds_qnty + Prod_taken_qnty
Row(0)("qnty") = Minus_qnty
End If
Or maybe simply this:
Dim Row() As Data.DataRow = ds.Tables(0).Select("Prodno = '" & ProdItem_No & "'")
If Row.Length > 0 Then
Row(0)("qnty") = Row(0)("qnty") + Prod_taken_qnty
End If

loop through 2 strings and combine VB 2010

i have a simple task i think
my code generates 2 strings
string A (separated by line feeds)
1
2
3
4
String B (separated by line feeds)
5
6
7
8
i am trying to figure out how to combine these separate strings into one as if they were two columns next to each other, separated by a comma
the result would be string C
1,5
2,6
3,7
4,8
Thanks!
How about something like?
Dim A As String = "1" & vbCrLf & "2" & vbCrLf & "3" & vbCrLf & "4"
Dim B As String = "5" & vbCrLf & "6" & vbCrLf & "7" & vbCrLf & "8"
Debug.Print(A)
Debug.Print(B)
Dim tmp As New List(Of String)
tmp.AddRange(A.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries))
Dim values() As String = B.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
For i As Integer = 0 To values.Length - 1
If i <= tmp.Count - 1 Then
tmp(i) = tmp(i) & "," & values(i)
Else
tmp.Add("," & values(i))
End If
Next
Dim C As String = String.Join(vbCrLf, tmp.ToArray)
Debug.Print(C)
Convert both strings to char[] (Char() - character array) (string.ToCharArray()).
Iterate thru the arrays.
You will need to check boundary conditions (e.g. what if the strings are different lengths).
'first string
Dim a As String = "abcd"
'second string
Dim b As String = "defghijk"
'Remove Line feeds
Dim tempA As String = a.Replace(vbLf, "")
Dim tempB As String = a.Replace(vbLf, "")
'Get the string with the larger size.
Dim largerSize As Integer = If(tempA.Length > tempB.Length, tempA.Length, tempB.Length)
'We use a string builder to build our new string
Dim sb As New StringBuilder()
'Loop on the larger size and only insert if inside range of string
For i As Integer = 0 To largerSize - 1
If i < tempA.Length Then
sb.Append(a(i))
sb.Append(",")
End If
If i < tempB.Length Then
sb.Append(b(i))
End If
sb.Append(vbLf)
Next
'this is the result
Dim combined As String = sb.ToString()
Edit answer to remove line feeds
Another Edit after string result edited
Another edit to make it VB.NET
I would use the wonderful Linq Zip! (I would first String.Split the 2 strings with the line-feed character) and then
Dim column1() As String = {"1", "2", "3", "4"}
Dim column2() As String = {"5", "6", "7", "8"}
Dim mixed= column1.Zip(column2, Function(first, second) first & "," & second)
edit:
oh, and then, if you want to have it back into 1 string, you can either use String.Join but Linq is fun too! So you can write :
Dim mixed= column1.Zip(column2, Function(first, second) first & "," & second)
.Select(i => i.Boo)
.Aggregate((i, j) => i + vbLf + j)
Did I mention that Linq is fun?

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)