Read and change combo-box selected item with 4 different possible values - vb.net

I have a multi-line textbox that the user can type into; the contents of which are supposed to drive the currently selected item in a combobox.
I have existing code that works for two items currently (Yes & No); however, I now need to make this extend to supporting four items. This is also updated by a timer every 3 seconds, in case if the user manually updated the text. The combobox cannot be typed in, instead it has preset selections.
Also the program is designed to edit properties files.
I'm a little unsure on how to go about doing so.
This is what works for 2 item changes:
Dim lines as Textbox1.lines()
Dim ach_tr As String = "announce-player-achievements=" 'stuff to be replaced by string ach_ttr
Dim ach_ttr As String = "" 'empty string to delete string ach_tr
Dim ach As String = lines(My.Settings.AnnouncePlayerAchievements)'line of string ach_tr
ach = ach.Replace(ach_tr, ach_ttr)'removes string ach_tr and leaves the value
If ach = "true" Then
achievements.SelectedItem = "Yes"
Else
achievements.SelectedItem = "No"
End If
I've tried these for 4 items:
Dim lines as Textbox1.lines()
Dim diff_tr As String = "difficulty="
Dim diff_ttr As String = ""
Dim diff As String = lines(My.Settings.Difficulty)
diff = diff.Replace(diff_tr, diff_ttr)
If diff = "0" Then
achievements.SelectedItem = "Peaceful"
End If
If diff = "1" Then
achievements.SelectedItem = "Easy"
End If
If diff = "2" Then
achievements.SelectedItem = "Normal"
End If
If diff = "3" Then
achievements.SelectedItem = "Hard"
End If
And This one:
Dim lines as Textbox1.lines()
Dim diff_tr As String = "difficulty="
Dim diff_ttr As String = ""
Dim diff As String = lines(My.Settings.Difficulty)
diff = diff.Replace(diff_tr, diff_ttr)
If diff = "0" Then
achievements.SelectedItem = "Peaceful"
Else
If diff = "1" Then
achievements.SelectedItem = "Easy"
Else
If diff = "2" Then
achievements.SelectedItem = "Normal"
Else
If diff = "3" Then
achievements.SelectedItem = "Hard"
End If
End If
End If
End If

You could do something akin to:
var difficultyMap = new Dictionary<string,string>
{
{"0", "Peaceful"},
{"1", "Easy"},
{"2", "Normal"},
{"3", "Hard"}
};
difficultyCombo.Items = difficultyMap.Values;
updateTimer.Tick += (s,e) => {
var text = inputTextBox.Text;
string found;
if (!difficultyMap.TryGetValue(text))
{
MessageBox.Show("unknown difficulty");
return;
}
difficultyCombo.SelectedItem = found;
};
This is in C# as I don't know VB very well, but the core concepts should map, I'm also not sure of your exact implementation or requirements, in essence I've done the following:
Created a dictionary that goes from the "numeric" difficulty type to the display type for the combo
Populated the combo using the display values from the dictionary
Whenever the update timer fires, I:
Get the text from the textbox
Try to find the matching difficulty in the dictionary
Display an error or update the combo
Adding n number of items to the combo and text input is trivial now, as you just add a new entry to the dictionary.

Edit: For future reference Heres a more compact version which works as well:
Public LineNum As Globals.LineNumEnum
Dim serveriptr As String = ("server-ip=")
Dim sipc As String = PropView.OutputRTF.Lines(LineNum.SerIP)
sipc = sipc.Replace(serveriptr, Nothing)
I found my problem. I was trying to change the wrong combobox lol. well at least I learned about dictionaries and the select case. Well thanks for your time.
This is the correct code lol:
Dim diff_tr As String = "difficulty="
Dim diff_ttr As String = ""
Dim diff As String = lines(My.Settings.Difficulty)
diff = diff.Replace(diff_tr, diff_ttr)
If diff = "0" Then
difficulty.SelectedItem = "Easy"
ElseIf diff = "1" Then
difficulty.SelectedItem = "Easy"
ElseIf diff = "2" Then
difficulty.SelectedItem = "Normal"
ElseIf diff = "3" Then
difficulty.SelectedItem = "Hard"
End If

Related

Load textfile containing names to a textbox

I am attempting to load a text file that contains a list of names into a text box using a button on the form. Also, I would like to display the following name after the button is pressed. I have been trying to successfully implement this code for several days however, my program loads all names at once. Would anyone be able to provide advice about loading text files?
Below is a copy of my code:
firstName.Multiline = True 'Variable contains first name.
lastName.Multiline = True 'Variable contains last name.
Dim fullName = "" 'Variable containing full name found in text file
Dim lines = IO.File.ReadAllLines("input.txt") 'loading input file located in Debug folder.
For Each i As String In lines
Dim fullNames = lines.Where(Function(line) line.Contains(" "))
If fullNames.Any() Then
Dim fullNamesSplit = fullNames.Select(Function(line) line.Split(" "c))
Dim firstNames = fullNamesSplit.Select(Function(line) line(0))
Dim lastNames = fullNamesSplit.Select(Function(line) line(1))
firstName.Lines = firstNames.ToArray()
lastName.Lines = lastNames.ToArray()
fullName = String.Join(Environment.NewLine, fullNames)
Else
firstName.Text = ""
lastName.Text = ""
End If
displayInfo.Items.Add(fullName)
Next
There's no loop. Load the names into an array, initialise an index variable to 0 and load the name at that index. Each time you click the Button, increment the index and load the name at that index. Once you reach the end, you can either wrap to the beginning or tell the user there are no more names. If you don't want to wrap then an even better option would be to load the names into a queue and then just dequeue on each click.
I have been able to display the names in order however I did not use a looping structure. However, the names are output multiple times in the text box after the button is clicked.
Dim i As Integer = 0
Private Sub NextAvName_Click(sender As Object, e As EventArgs) Handles nextAvName.Click
firstName.Multiline = True 'Variable contains first name.
lastName.Multiline = True 'Variable contains last name.
Dim fullName = "" 'Variable containing full name found in text file
Dim lines = IO.File.ReadAllLines("input.txt") 'loading input file located in Debug folder.
lines = lines.ToArray
Dim element As String
element = lines(i)
Dim fullNames = element.Where(Function(line) element.Contains(" "))
If fullNames.Any() Then
Dim fullNamesSplit = fullNames.Select(Function(line) element.Split(" "c))
Dim firstNames = fullNamesSplit.Select(Function(line) line(0))
Dim lastNames = fullNamesSplit.Select(Function(line) line(1))
firstName.Lines = firstNames.ToArray()
lastName.Lines = lastNames.ToArray()
fullName = String.Join(Environment.NewLine, fullNames)
Else
firstName.Text = ""
lastName.Text = ""
End If
displayInfo.Items.Add(fullName)
i = i + 1

Is there a way to identify which dropdown boxes aren't empty when hitting 'search' on a VBA GUI?

I'm working on an application in VBA that takes in information from an excel sheet, populates a dropdown combobox, then based on the selected information from the dropbox, retrieves the full information for matching values. There are 6 dropboxes and I'm looking for a way to find out which dropboxes have a value (not empty) without rewriting dozens of if statements with the same code but different conditions (i.e combo 1 and 3 have values, so the program will only look for the records based on those two selected fields)
I know this can be achieved with re-writing if statements, but I'm hoping there's an easier way that doesn't take hours?
Private Sub Search_Page1_Click()
Dim year As String
Dim location As String
Dim snap As String
Dim city As String
Dim group As String
Dim endyear As String
year = Multipage1.Cmb_Year.Value
location = Multipage1.Cmb_Location.Value
snap = Multipage1.Cmb_Snapshot.Value
city = Multipage1.Cmb_City.Value
group = Multipage1.Cmb_Group.Value
endyear = Multipage1.Cmb_LeaseEnd.Value
If year = Empty And location = Empty And snap = Empty And city = Empty
And group = Empty And endyear = Empty Then
MsgBox ("Please fill in at least one field")
End If
End Sub
If you can work with a Collection of ComboBox controls, then whip up a custom function like and call it like:
Dim populatedBoxes as New Collection
Set populatedBoxes = GetPopulatedThings(Multipage1, "ComboBox")
Dim cb as MSForms.ComboBox
For Each cb in populatedBoxes
MsgBox cb.Value
Next
In your code, you could replace:
If year = Empty And location = Empty And snap = Empty And city = Empty And group = Empty And endyear = Empty Then
With this:
Set populatedBoxes = GetPopulatedThings(Multipage1, "ComboBox")
If populatedBoxes.Count = 0 Then Exit Sub
Here's the function:
Private Function GetPopulatedThings(container As Object, Optional ctrlType As String = "ComboBox") As Collection
Dim c As New Collection
Dim ctrl As MSForms.Control
For Each ctrl In container.Controls
If TypeName(ctrl) = ctrlType Then
Select Case ctrlType
Case "ComboBox"
If ctrl.ListIndex > -1 Then
c.Add ctrl
End If
Case Else
' TBD
' Additional cases will require separate logic...
End Select
End If
Next
Set GetPopulatedThings = c
End Function

Populate Treeview with data from string split with "\"

I have a large list which contains value like
List(0) = "Drive\First1\Folder2\Folder3"
List(1) = "Drive\Second2"
List(2) = "Drive\SubFolder1\ChildSubFolder"
Dim List = Split("Drive\First1\Folder2\Folder3", "\")
ParentNode = TreeView1.Nodes.Add(List(0))
For x = 1 To List.Count - 1
ParentNode.Nodes.Add(List(x))
Next
I am very confused about how to populate treeview control in vb.net
Can someone help me on this? Please. Thanks in advance.
You need two loops. One loop for the list, the second one to loop through the items that are separated by the slash. The tricky part is to differentiate between a "root node", which belongs to the TreeView control itself, and a "child node" that belongs to a parent node within that collection.
Once you have that figured out, you simply examine to see if the node already exists, and if it does, use that, otherwise, add it to the collection.
For Each item As String In List
Dim activeNode As TreeNode = Nothing
Dim nodeItems As TreeNodeCollection = Nothing
Dim subItems() As String = item.Split("\"c)
For i As Integer = 0 To subItems.Length - 1
nodeItems = If(i = 0, TreeView1.Nodes, activeNode.Nodes)
If nodeItems.ContainsKey(subItems(i)) Then
activeNode = nodeItems(subItems(i))
Else
activeNode = nodeItems.Add(subItems(i), subItems(i))
End If
Next
Next
I too find the answer but my code gives incorrect results... and #LarsTech code works perfectly. Thanks again LarsTech
Dim List(3) As String
List(0) = "Drive\First1\Folder2\Folder3"
List(1) = "Drive\Second2"
List(2) = "Drive\Second3\Folder4"
List(3) = "xDrive\Folder4\Folder5"
For Each ListItem In List
Dim Folders() = Split(ListItem, "\")
For i = 1 To Folders.Count - 1
Dim pNode = TreeView1.Nodes.Find(Folders(i - 1), True)
If pNode.Count = 0 Then
Dim pNode1 = TreeView1.Nodes.Add(Folders(i - 1), Folders(i - 1))
pNode1.Nodes.Add(Folders(i), Folders(i))
Else
If pNode(0).Nodes.Find(Folders(i), True).Count = 0 Then
pNode(0).Nodes.Add(Folders(i), Folders(i))
End If
End If
Next
Next

How can I seperate the values in the textbox to show in different labels using button?

i want to be able to separate the values in a textbox and display the separated values in different labels using a button
this is what i want to happen:
input "Ac2O3" on textbox
Be able to separate "Ac", "2", "O", and "3".
Show the separated values in different textboxes using a button
im using visual basic 2012
im sorry im still new to this
thanks in advance!!
You can access different character of the string with the index.
Dim input As String = "Ac2O3"
Dim part1 As String = input(0) & input(1)
Dim part2 As String = input(2)
Dim part3 As String = input(3)
Dim part4 As String = input(4)
If you don't know how to handle the button event or how to display text in a textbox, that would be different questions.
This code creates a structure called Element to make the results from the function clearer - add this to your main class that the function is going to be placed in. The main function takes a string as it's input and produced a list of structures of Element as it's output. There probably are shorter ways to do this, but I'm a fairly basic programmer who likes a puzzle - hope this helps - Dont forget to accept the answer by clicking on the tick. If you have any queries please dont hesitate to ask
Structure Element
Dim symbol As String
Dim elementCount As Int16
End Structure
Function ParseFormula(ByVal compoundString As String) As List(Of Element)
Dim tempParseFormula = New List(Of Element)
Dim firstLetter As String = "[A-Z]"
Dim secondLetter As String = "[a-z]"
Dim number As String = "[0-9]"
Dim tempElementCount As String = ""
Dim maxIndex As String = compoundString.Length - 1
Dim i As Integer = 0
Dim parsedElement As New Element
While i <= maxIndex
Dim tempChar As String = compoundString(i)
Select Case True
Case tempChar Like firstLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like secondLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like number
tempElementCount = tempElementCount & tempChar
End Select
If i = maxIndex Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
Exit While
End If
i += 1
If compoundString(i) Like firstLetter Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
End If
End While
Return tempParseFormula
End Function

Separating lines to textbox (vb 2008) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to set like this
In first textbox I want 1st line
in second textbox I want 2nd line
and so one...
prezime.Text = "Vukmirovic" 'I want this to show in textbox
ime.Text = ""
jmbg.Text = ""
pol.Text = ""
daniz.Text = ""
meseciz.Text = ""
godinaiz.Text = ""
danr.Text = ""
mesecr.Text = ""
godinar.Text = ""
danvd.Text = ""
mesecvd.Text = ""
godinavd.Text = ""
regbr.Text = ""
brojtel.Text = ""
adresa.Text = ""
grad.Text = ""
opstina.Text = "" <code>
OK , i writed down the code so that Prezime: is replaced with nothing. I imported
System.Text.RegularExpressions
Now i just have to set that first line is set for prezime.text , second for ime.text and so one , help :)
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text, "Prezime: ", "")
Assuming you are using .NET
'...
Dim i As Integer = 0
Dim myFile As String = "C:\Temp\infile.txt"
'it would be good to add a try/catch here in case you get an io error
Dim lines() As String = System.IO.File.ReadAllLines(myFile)
prezime.Text = splitter(lines(i))
ime.Text = splitter(lines(++i))
'do the same for other text boxes
'you need to code the lines in the same order as input file values
lastRow.Text = splitter(lines(++i))
'...
Private Shared Function splitter(ByVal parmLine As String) As String
'split the passed string into 2 srings using the : as a separator
Dim words() As String = parmLine.Split(":")
'test to see you have 2 words returned. If not, error
If (words.Length < 2) Then
Return "Error reading from file - Expected 2 tokens spearated by : but found 1"
End If
'you don't care about the first word it is the field name. Return the 2nd
Return words(1).Trim
End Function
Assuming you're using a textbox to hold your file's content.
Public Function whichtxt(ByVal line As Integer) As TextBox
If line = 0 Then
Return TextBox2
ElseIf line = 1 Then
Return TextBox3
'And so on...
Else
Return Nothing
End If
End Function
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To TextBox1.Lines.Length - 1
Dim s As String = TextBox1.Lines(i)
whichtxt(i).Text = s
Next
First we'll write a function to parse the actual part of the input we want from each line:
Private Function GetDataFromLine(line As String) As String
'Find everything before and including ': ' and remove it
Return Regex.Replace(line, ".*: ", String.Empty)
End Function
Note: Calling the static regex methods versus creating a regex instance has some performance loss, see this answer for more details.
Then we'll read all the lines from the file and put them in the appropriate fields:
Dim lines = File.ReadAllLines("myfile.txt")
prezime.Text = GetDataFromLine(lines(0))
ime.Text = GetDataFromLine(lines(1))
jmbg.Text = GetDataFromLine(lines(2))
'...
Another possible way to solve this, would be to map your input data into a dictionary that would look like this:
"Prezime" => "Vukmirovic"
"Ime" => "Nemanja"
...
and then do something like:
prezime.Text = inputDictionary("Prezime")
You'd have to write a function that'd map the input file to a dictionary.