How to store textbox input into a two dimensional array? - vb.net

okay so i have two textboxes for user input, and i need help storing these into a single two dimensional array.
for 49 columns and two rows (states, capitals)
i already declared the array to:
Dim states(49,1) as string
states(0,0)= textbox1.text
states(0,1) = textbox2.text
im not sure what else to do because i have
am i storing this right? im not sure what more to do to store the rest of input into the array.
any help would be appreciated. thank you!

Declare module/class scope variables:
Dim states(49,1) as string
Dim nextInd as Integer = 0
Then in your button click handler:
If nextInd <= 49 Then ' Make sure you are not trying to fill values past the dimensions of the array
states(nextInd, 0) = textbox1.text
states(nextInd, 1) = textbox2.text
nextInd += 1 ' To increment the next index to use by 1
textbox1.text = ""
textbox2.text = ""
End If
And then to display the contents of the array, you need a loop:
' Use a string builder so you can modify the same string object to show it all together in the message box
Dim contents As New StringBuilder("")
For st = 0 To 49
contents.Append(states(st, 0) & ": " & states(st, 1) & Environment.NewLine)
' Or however you want To format it
Next
MessageBox.Show(Me, contents) ' MsgBox is old - use MessageBox instead

Related

How to remove and re-add a comma in a string?

I have a textbox on my form that when a button is clicked, it is populated with numbers that are separated by a comma. I have a delete button that will remove the numbers with the comma one at a time. My question is how would I go about re-adding the comma every time i hit the add button, again? I thought i could add the comma in the beginning in an if statement, but its adding two commas, every time I hit the add button, if I delete, then try to re- add.
here is what i have :
if textbox1.text = "" then
textbox1.text = textbox1.text & testNumber(combobox.selecteditem) & ","
else
textbox1.text = "," & textbox1.text & testnumber(combox.selecteditem)
end if
The contents of the textbox should only be a view of a more appropriate underlying data structure. For example, you might have a List(Of Integer) or Queue(Of Integer) as a member of your form. When you add or remove an item you first update the collection, then you set the text. For example:
Add:
MyList.Add(nextNumber)
textbox1.text = String.Join(","c, MyList)
Remove:
MyList.RemoveAt(MyList.Count - 1);
textbox1.text = String.Join(","c, MyList)
Do this even if they want the ability to update the textbox directly. It's just in this case you must also be able to validate and parse the contents of the textbox to recreate the list.
First of all, storing numbers in a comma delimited string is pretty strange requirement. I'd suggest to store numbers in a proper data type, such as: List(Of Integer).
Assuming that testnumber function returns integer...
'define at the top of Form's module:
Private myNumbers As List(Of Integer) = New List(Of Integer)()
'copy-paste below method to the form's module
Private Function GetCommaSeparatedNumbers() As String
Return String.Join(",", myNumbers)
End Function
'finally:
'to add number
myNumbers.Add(testnumber(combox.selecteditem))
'to remove number
myNumbers.Remove(testnumber(combox.selecteditem))
'to display numbers
Me.textbox1.Text = GetCommaSeparatedNumbers()
If you would like to check out if number already exists on the list, use:
If myNumbers.Contains(testnumber(combox.selecteditem)) Then
'display warning
Else
'add number
End If
Good luck!
Your code is initial testing textbox1.Text = "" and then, if that is true, it is then doing textbox1.Text = textbox1.Text & testNumber(combobox.SelectedItem) & ",", but since textbox1.Text is "" this is the equivalent of:
textbox1.Text = "" & testNumber(combobox.SelectedItem) & ","
That really means you are adding a comma when you only have one number.
This is what you should be doing:
if textbox1.Text = "" then
textbox1.Text = testNumber(combobox.SelectedItem)
else
textbox1.Text = textbox1.Text & "," & testnumber(combox.SelectedItem)
end if
To add a number, I'd do it with this line:
TextBox1.AppendText(If(TextBox1.TextLength = 0, "", ",") & testNumber(ComboBox.SelectedItem))
Are numbers being deleted from the beginning or end?...or is a "selected" number from anywhere in the list being deleted?

VBA in ACCESS. Trouble with ComboBox

I have some ComboBoxes on my FORM. One of them have items as a result of SQL request from field PG (cbPG.RowSource = "SELECT DISTINCT W_report.PG FROM W_report WHERE ......) The size of the field is byte.
After reqest
User can select one of the variant or can list several comma-separated (2,4,5,7,11,13).
Correct value
The resulting ComboBox.value is used in a procedure similar to selecting pages for printing. Everything works correctly until changes are made to the event handler of cbPG. Then the values are automatically rounded (if one comma)
wrong value
or an error "The entered value is not appropriate for this field" occurs (if a few commas) and I have to copy cbPG from the backup because I can't find a property that changes format of cbPG.value to byte.
Here is part of program that use my ComboBox
Public Function MnogoListov(str As String) As String
Dim i, j As Integer
Dim res As String
Dim listArr() As String
res = ""
ReDim listArr(Len(str)) As String
For i = 1 To Len(str)
If Mid(str, i, 1) <> "," And Mid(str, i, 1) <> "." Then
listArr(j) = listArr(j) & Mid(str, i, 1)
Else
j = j + 1
End If
Next
For i = 0 To j
If i = 0 Then
res = listArr(i)
Else
res = res & " OR W_report.PG = " & listArr(i) End If
Next
MnogoListov = res
End Function
You can't do that. A combobox is for selecting one value from several.
So, either use a multi-select listbox or a simple textbox where you - similar to selecting pages for printing - parse the inputted values to obtain the sequence (list) of items (pages).

How can i check for a character after certain text within a listbox?

How can i check for a character after other text within a listbox?
e.g
Listbox contents:
Key1: V
Key2: F
Key3: S
Key4: H
How do I find what comes after Key1-4:?
Key1-4 will always be the same however what comes after that will be user defined.
I figured out how to save checkboxes as theres only 2 values to choose from, although user defined textboxes is what im struggling with. (I have searched for solutions but none seemed to work for me)
Usage:
Form1_Load
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
Which textbox1.text would then contain V / whatever the user defined.
I did try something that kind of worked:
Form1_Load
Dim UsersKey as string = "V"
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
but i'm not sure how to add additional letters / numbers to "V", then output that specific number/letter to the textbox. (I have special characters blocked)
Reasoning I need this is because I have created a custom save settings which saves on exit and loads with form1 as the built in save settings doesn't have much customization.
e.g Can't choose save path, when filename is changed a new user.config is generated along with old settings lost.
Look at regular expressions for this.
Using the keys from your sample:
Dim keys As String = "VFSH"
Dim exp As New RegEx("Key[1-4]: ([" & keys& "])")
For Each item As String in ListBox1.Items
Dim result = exp.Match(item)
If result.Success Then
TextBox1.Text = result.Groups(1).Value
End If
Next
It's not clear to me how your ListBoxes work. If you might find, for example, "Key 2:" inside ListBox1 that you need to ignore, you will want to change the [1-4] part of the expression to be more specific.
Additionally, if you're just trying to exclude unicode or punctuation, you could also go with ranges:
Dim keys As String = "A-Za-z0-9"
If you are supporting a broader set of characters, there are some you must be careful with: ], \, ^, and - can all have special meanings inside of a regular expression character class.
You have multiple keys, I assume you have multiple textboxes to display the results?
Then something like this would work. Loop thru the total number of keys, inside that you loop thru the alphabet. When you find a match, output to the correct textbox:
Dim UsersKey As String
For i As Integer = 1 To 4
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
UsersKey = c
If ListBox1.Items.Contains("Key" & i & ": " & UsersKey) Then
Select Case i
Case 1
TextBox1.Text = UsersKey
Case 2
TextBox2.Text = UsersKey
Case 3
TextBox3.Text = UsersKey
Case 4
TextBox4.Text = UsersKey
End Select
Exit For 'match found so exit inner loop
End If
Next
Next
Also, you say your settings are lost when the filename is changed. I assume when the version changes? The Settings has an upgrade method to read from a previous version. If you add an UpgradeSettings boolean option and set it to True and then do this at the start of your app, it will load the settings from a previous version:
If My.Settings.UpgradeSettings = True Then
My.Settings.Upgrade()
My.Settings.Reload()
My.Settings.UpgradeSettings = False
My.Settings.Save()
End If
Updated Answer:
Instead of using a listtbox, read the settings file line by line and output the results to the correct textbox based on the key...something like this:
Dim settingsFile As String = "C:\settings.txt"
If IO.File.Exists(settingsFile) Then
For Each line As String In IO.File.ReadLines(settingsFile)
Dim params() As String = Split(line, ":")
If params.Length = 2 Then
params(0) = params(0).Trim
params(1) = params(1).Trim
Select Case params(0)
Case "Key1"
Textbox1.Text = params(1)
Case "Key2"
Textbox2.Text = params(1)
End Select
End If
Next line
End If
You can associate text box with a key via its Name or Tag property. Lets say you use Name. In this case TextBox2 is associated with key2. TextBox[N] <-> Key[N]
Using this principle the code will look like this [considering that your list item is string]
Sub Test()
If ListBox1.SelectedIndex = -1 Then Return
Dim data[] As String = DirectCast(ListBox1.SelectedItem, string).Split(new char(){":"})
Dim key As String = data(0).Substring(3)
Dim val As String = data(1).Trim()
' you can use one of the known techniques to get control on which your texbox sits.
' I omit this step and assume "Surface1" being a control on which your text boxes sit
DirectCast(
(From ctrl In Surface1.Controls
Where ctrl.Name = "TextBox" & key
Select ctrl).First()), TextBox).Text = val
End Sub
As you can see, using principle I just explained, you have little parsing and what is important, there is no growing Select case if, lets say, you get 20 text boxes. You can add as many text boxes and as many corresponding list items as you wish, the code need not change.

How do I display the result of a loop on a new line in a text box?

Basically, how do I write a new line in a text box, keeping the existing information as well.
If I have for loop,
For i As Integer = 1 To 10
Dim result = i
i = i + 1
textbox1.text = result
Next
This will display '10' in the textbox. I want it to be like:
1
2
3
4
...
First, your TextBox must allow multiple lines. This is a property of the textbox control that you can set from the designer or from the code. You may want to ensure that a scroll bar is there to scroll in case the height is not large enough.
If you want to set the properties from code, use this code in the Load event of the form.
' Set the Multiline property to true.
textBox1.Multiline = True
' Add vertical scroll bars to the TextBox control.
textBox1.ScrollBars = ScrollBars.Vertical
' Change the height of the textbox so that it could accomodate the lines
TextBox1.Height = 120
Now, your approach had a major problem in this line:
textbox1.text = result
The way you coded it, every new value of i, would overwrite the old value. What you want to do is to first construct a string, then send the entire string to the TextBox control. This is not required had you been using Console.WriteLine method.
Method 1
Dim s as string
s=""
For i As Integer = 1 To 10
s = s & Environment.Newline & i.ToString() 'we use Environment.NewLine to force new line
Next i
textbox1.text = s
Method 2
.NET offers a class to handle strings better than the way we did before. It won't matter in your case but it is the efficient way to handle concatenation when volume is large and/or performance matters
Dim s as new System.Text.StringBuilder() 'Initialize stringbuilder instance
For i As Integer = 1 To 10
s.AppendLine (i.ToString()) 'We use stringbuilder to concat. and inser line feed
Next i
textbox1.text = s.ToString()
Note: If you want double spacing then you need to add a linefeed (using & ) to both of the above methods.
Something like this should work:
For i As Integer = 1 To 10
if i = 1 then
textbox1.text = i
else
textbox1.text &= vbcrlf & i
end if
Next
For i = 1 To 10
textbox1.AppendText(vbNewLine & i)
Next

Visual Basic Loop and Display one line at a time

I'm using visual studios 2008, VB9 and I am trying to write an app that basically performs calculations on a set of data input by a user. During the calculations, I want to display the data at each step, and have it retained in the display area on the GUI (not overwritten by the next data being displayed).
For example:
UserInput = 1
Do
UserInput += 1
OutputLabel.Text = "UserInput " & UserInput
Loop Until UserInput = 5
and the output would look like
UserInput 1
UserInput 2
UserInput 3
UserInput 4
UserInput 5
I tried this, and other loop structures and can't seem to get things right. The actual app is a bit more sophisticated, but the example serves well for logical purposes.
Any tips are welcome, thanks!
This is the simple version:
Dim delimiter as String = ""
For UserInput As Integer = 1 To 5
OutputLabel.Text &= String.Format("{0}UserInput {1}", delimiter, UserInput)
delimiter = " "
Next
However, there are two problems with it and others like it (including every other answer given so far):
It creates a lot of extra strings
Since it's in a loop the label won't be able to process any paint events to update itself until you finish all of your processing.
So you may as well just do this:
Dim sb As New StringBuilder()
Dim delimiter As String = ""
For UserInput As Integer = 1 To 5
sb.AppendFormat("{0}UserInput {1}", delimiter, UserInput)
delimiter = " "
Next
OutputLabel.Text = sb.ToString()
And if you really want to have fun you can just do something like this (no loop required!):
OutputLabel.Text = Enumerable.Range(1, 5).Aggregate(Of String)("", Function(s, i) s & String.Format("UserInput {0} ", i))
You need to concatenate the value in OutputLabel.Text.
OutputLabel.Text &= "UserInput " & UserInput
You might also want to reset it before the loop: OutputLabel.Text = ""
If you need an iterated index you can try something like the following
For I As Integer = 1 To 5
If I > 1 Then OutputLabel.Text &= " "
OutputLabel.Text &= "UserInput " & I.ToString()
End For
If you have user inputs in a collection, you might better be served by using ForEach loop.
Do you need to do it in a GUI? If it is simply processing and putting out rows like that, maybe you should consider a console application, in which case it becomes REALLY easy, in simply calling
Console.WriteLine("my string")
All of these ways actually work really well but the one that fit my situation the best was this:
Do
Dim OutputString as String
Application.DoEvents() 'to make things paint actively
UserInput += 1
OutputString = String.Format("{0}", UserInput)
ListBox.Items.Add(OutputString)
Loop Until UserInput = 5
I changed things to a listbox but tried this same method with textboxes and labels, with some tweaks, they all worked very well. Thanks for all your help!
I'd use a more appropriate control, like richtextbox
Dim UserInput As Integer = 0
Const userDone As Integer = 5
RichTextBox1.Clear()
Do
RichTextBox1.AppendText(String.Format("User input {0:n0} ", UserInput))
RichTextBox1.AppendText(Environment.NewLine)
RichTextBox1.Refresh() 'the data at each step
UserInput += 1
Loop Until UserInput = userDone