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

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?

Related

Removing a Duplicate Item from ListBox converted into a string

I have an issue where, when I take the items from my ListBox, and convert them into a single-line string, it duplicates the last item. My goal is for it to take just the items from the ListBox, and convert it into a single line of text, seperated by commas (,).
It took me a while, but I found some code on this thread, and it works for the most part, but the last item is always duplicated when converted to a string. The code that I am using is:
Dim item As Object
Dim List As String
' Other unrelated code
' Credit: T0AD - https://www.tek-tips.com/viewthread.cfm?qid=678275
For Each item In Form1.ListBox1_lstbox.Items
List &= item & ","
Next
'To remove the last comma.
List &= item.SubString(0, item.Length - 0)
' This is weird, but setting item.Length - 1 actually removes two characters.
' Add text to textbox
TextBox1.Text = List
I have a feeling that it has to deal with the code that removes the comma, as it is an &= that calls the item Dim again. But I can't seem to figure out what to do.
An example of the output would be something like this: Item1,Item2,Item3,Item3
When I just want this: Item1,Item2,Item3
Your problem is with this line.
List &= item.SubString(0, item.Length - 0)
You are adding another string to List with the &=. The string you are adding is the final value of item from the For Each loop.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ListBox1.Items.Count = 0 Then
MessageBox.Show("There are no items in the list box.")
Exit Sub
End If
Dim List As String = ""
For Each item In ListBox1.Items
List &= item.ToString & ","
Next
List = List.Substring(0, List.Length - 1)
TextBox1.Text = List
End Sub
Additional solution provided by #Andrew Morton in comments, which doesn't require the ListBox to contain items.
TextBox1.Text = String.Join(",", ListBox1.Items.Cast(Of Object))

How to store textbox input into a two dimensional array?

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

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.

Split method with line breaker vb.net

I have a checkedlistbox to fill with the textbox values, but i have some issues cause if i paste the text from the textbox in a word file it comes with linebreakers, and not just spaces . Maybe that's why the checked list box is not being filled properly.
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
Dim separated = TextBox2.Text.Split(vbNewLine & " ")
CheckedListBox1.Items.Clear()
CheckedListBox1.Items.AddRange(separated)
CheckedListBox1.Items.Remove(vbCrLf)
CheckedListBox1.Items.Remove("#")
CheckedListBox1.Items.Remove("PI")
End Sub
How can i get rid of this problem? If i paste the values in word they come like this:
You are currently separating the string where a space is followed by a new line. Any other spaces around this string are included in the output. You want to use a different version of Split, listing each character, so that ANY of those characters can be used to split the string:
Dim separated = TextBox2.Text.Split(vbCr, vbLf, vbTab, " "c)
This will treat one or more of space, tab, line feed OR carriage return as a split and will not include any of them in the strings it returns. It will however return a number of empty strings, so you will need to add the strings individually, filtering these out. The rest of the code can be replaced by this:
CheckedListBox1.Items.Clear()
For Each item In separated
If item <> "" Then CheckedListBox1.Items.Add(item)
Next
Get rid of all spaces and then split
Dim separated = TextBox2.Text.Replace(" ", "").Split(vbNewLine)
UPDATE to remove the tabs
char tabs = '\u0009';
Dim separated = TextBox2.Text.Replace(" ", "").Replace(tabs, "").Split(vbNewLine)
You need to remove all items that are not required prior to splitting.
SO... based on your example
char tabs = '\u0009';
StrippedText = TextBox2.Text.Replace(" ", "").Replace(tabs, "").Replace("P1" & vbCRLF & vbCRLF, "").Replace(vbCRLF & "#" & vbCRLF, "")
Dim separated = StrippedText.Split(vbNewLine)

Get only the line of text that contains the given word VB2010.net

I have a text file on my website and I download the whole string via webclient.downloadstring.
The text file contains this :
cookies,dishes,candy,(new line)
back,forward,refresh,(new line)
mail,media,mute,
This is just an example it's not the actual string , but it will do for help purposes.
What I want is I want to download the whole string , find the line that contains the word that was entered by the user in a textbox, get that line into a string, then I want to use the string.split with as delimiter the "," and output each word that is in the string into an richtextbox.
Now here is the code that I have used (some fields are removed for privacy reasons).
If TextBox1.TextLength > 0 Then
words = web.DownloadString("webadress here")
If words.Contains(TextBox1.Text) Then
'retrieval code here
Dim length As Integer = TextBox1.TextLength
Dim word As String
word = words.Substring(length + 1) // the plus 1 is for the ","
Dim cred() As String
cred = word.Split(",")
RichTextBox1.Text = "Your word: " + cred(0) + vbCr + "Your other word: " + cred(1)
Else
MsgBox("Sorry, but we could not find the word you have entered", MsgBoxStyle.Critical)
End If
Else
MsgBox("Please fill in an word", MsgBoxStyle.Critical)
End If
Now it works and no errors , but it only works for line 1 and not on line 2 or 3
what am I doing wrong ?
It's because the string words also contains the new line characters that you seem to be omitting in your code. You should first split words with the delimiter \n (or \r\n, depending on the platform), like this:
Dim lines() As String = words.Split("\n")
After that, you have an array of strings, each element representing a single line. Loop it through like this:
For Each line As String In lines
If line.Contains(TextBox1.Text) Then
'retrieval code here
End If
Next
Smi's answer is correct, but since you're using VB you need to split on vbNewLine. \n and \r are for use in C#. I get tripped up by that a lot.
Another way to do this is to use regular expressions. A regular expression match can both find the word you want and return the line that contains it in a single step.
Barely tested sample below. I couldn't quite figure out if your code was doing what you said it should be doing so I improvised based on your description.
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub ButtonFind_Click(sender As System.Object, e As System.EventArgs) Handles ButtonFind.Click
Dim downloadedString As String
downloadedString = "cookies,dishes,candy," _
& vbNewLine & "back,forward,refresh," _
& vbNewLine & "mail,media,mute,"
'Use the regular expression anchor characters (^$) to match a line that contains the given text.
Dim wordToFind As String = TextBox1.Text & "," 'Include the comma that comes after each word to avoid partial matches.
Dim pattern As String = "^.*" & wordToFind & ".*$"
Dim rx As Regex = New Regex(pattern, RegexOptions.Multiline + RegexOptions.IgnoreCase)
Dim M As Match = rx.Match(downloadedString)
'M will either be Match.Empty (no matching word was found),
'or it will be the matching line.
If M IsNot Match.Empty Then
Dim words() As String = M.Value.Split(","c)
RichTextBox1.Clear()
For Each word As String In words
If Not String.IsNullOrEmpty(word) Then
RichTextBox1.AppendText(word & vbNewLine)
End If
Next
Else
RichTextBox1.Text = "No match found."
End If
End Sub
End Class