VB.net Using a string to change something.Text - vb.net

I need to work in VB.net for school and have encountered a problem.
The program works like this:
I've got a store page with buttons to buy them, they each have a name with the item and "_buy" after it. So if I wanted to buy a laptop, I'd press a button named laptop_buy.
What I want then is to make the event call the fuction Buy(laptop), so I can use the laptop ID later on.
I also have things named like laptop_level and laptop_price. I want to change them when I click the button. So I created this function:
Private Sub laptop_buy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles laptop_buy.Click
Buy("laptop")
End Sub
And
Function Buy(ByVal item)
Dim itemlevel As String = item + "_level.Text"
itemlevel += 1
End Function
So this should change the laptop_level.Text when I click laptop_buy.
But it isn't working.
Help is greatly appriciated!

You can use ControlCollenction.Find method to get your label.
Then you need to cast it's text value to Integer (I recommend using Int32.TryParse method for that) and then add 1 and return the result to the label text. Something like this should do the trick.
Sub Buy(ByVal item As String)
Dim level As Inetger
Dim ItemLabel as Label;
Dim ChildControls As Control() = Me.Controls.Find(item & "_level", True)
If ChildControls.Length > 0 Then
ItemLabel = ChildControls(0)
End If
If not isNothing(ItemLabel) AndAlso Int32.TryParse(ItemLabel.Text, level) Then
ItemLabel.Text = (Level + 1).ToString
End If
End Sub
Note: Code was written directly here, and it's been a long time since my vb.net days, so there might be some mistakes in the code.

Your trying to add 1 to a string.
A 'String' is a series of text characters, so the '1' in your text box is the character '1' not the number. You need to first conver the text into an 'integer'
Try:
dim itemlevel as integer = TryCast(item, integer)
If IsNothing(itemlevel) = false then
itemlevel = itemlevel + 1
Return itemlevel
end if
MSDN TryCast

Related

Issue with ByVal and Arrays in Functions (VB.NET)

I've ran into an issue with my code for the last week or so, and its been killing me trying to figure out what's wrong with it. I've extracted and isolated the issue from my main project, but the issue still isn't apparent.
Essentially, I have a function that usually does a lot of stuff, but in this example just changes 1 element in an array called FalseTable. Now, I have set this variable to be ByVal, meaning the original variable (ie: TrueTable) shouldn't change, however, it does! Here is the full code:
Dim TrueTable(7) As Char
Sub Main()
Dim FalseTable(7) As Char
For x = 0 To 7
TrueTable(x) = "T"
Next
For x = 0 To 7
FalseTable(x) = "F"
Next
Console.WriteLine("before")
For x = 0 To 7
Console.Write(TrueTable(x))
Next
Console.WriteLine()
Test(TrueTable)
Console.WriteLine("result")
For x = 0 To 7
Console.Write(TrueTable(x))
Next
Console.WriteLine()
Console.ReadLine()
End Sub
Function Test(ByVal FalseTable() As Char) As Char()
FalseTable(0) = "0"
Return FalseTable
End Function
Now, I used to think that it was the repetition of the name "FalseTable" in the function, however even if I change the function to:
Function Test(ByVal SomeTable() As Char) As Char()
SomeTable(0) = "0"
Return SomeTable
End Function
And not modify the rest, the issue still persists - for some reason, TrueTable is being updated when it shouldn't due to the ByVal status.
Any help with this would be greatly appreciated; it's probably something stupid that I've overlooked, but it's pulling my hair out!!
Many thanks,
Alfie :)
If you don't want to change the TrueTable, define another Array and copy TrueTable to it.
Here's the code you can refer to.
Dim TrueTable(7) As Char
Dim TrueTable2(7) As Char
Sub Main()
For x = 0 To 7
TrueTable(x) = "T"c
Next
Console.WriteLine("before")
For x = 0 To 7
Console.Write(TrueTable(x))
Next
Console.WriteLine()
TrueTable.CopyTo(TrueTable2, 0)
Test(TrueTable2)
Console.WriteLine("result")
For x = 0 To 7
Console.Write(TrueTable(x))
Next
Console.WriteLine()
Console.ReadLine()
End Sub
Result:
To understand why that happens just imagine this scenario.
You have a regular TextBox1 (this will be your TrueTable), now you want to pass the object TextBox1 to a function, something like this:
Function Test(ByVal TextBoxAnything as TextBox) As String
TextBoxAnything.Text = "0"
Return ""
End Function
Do you understand that you're passing thru TextBox1 and once inside the function Test the object TextBoxAnything is just TextBox1, anything you do to TextBoxAnything you're just doing it to TextBox1. TextBoxAnything doesn't exist, it just points to Textbox1. That's why the value of your TrueTable is also changed.

calling a method from another class in vb.net

i have an external class(colorCode.vb) in same project as my main form.vb.
My objective is to send a value as argument as i call a method in the colorCode.vb class, and use the value returned by the method. I don't know if its logically possible . Here i tried this but failed.
in my colorCode.vb Class i have this codes:
Public Sub getValue(ByVal itemCode As Integer)
Dim codeVal() As Integer = {9999, 3034, 3040, 3035}
Dim colorVal As String
For counter As Integer = 0 To codeVal.Count Step 1
If (itemCode = codeVal(counter)) Then
Select Case codeVal(counter)
Case 9999
colorVal = "BRILLIANT WHITE EMULSION"
Case 3034
colorVal = "OFF-WHITE EMULSION"
End Select
End If
Next
End Sub
and in my main form.vb i did this
Private Sub descTextBox_TextChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles descTextBox.TextChanged
Dim colorDesc As colorCode = New colorCode()
Dim itemCode As Integer = Integer.Parse(itemCodeTextBox.Text)
descTextBox.Text = colorDesc.getValue(itemCode)'this line triggers an error.
End Sub
please i need some help here. already running nuts
Please turn on Option Strict. This is a 2 part process. First for the current project - In Solution Explorer double click My Project. Choose Compile on the left. In the Option Strict drop-down select ON. Second for future projects - Go to the Tools Menu -> Options -> Projects and Solutions -> VB Defaults. In the Option Strict drop-down select ON. This will save you from bugs at runtime.
Subs in vb.net do not return values. You need a Function. Instead of looping through the array you can just check if the array contains itemCode and if it does proceed with the Select Case.
Do not put your code in the text changed. It will run every time a character is entered before your user has a chance to enter the entire code. Create a button and use that. Use .TryParse to validate the input. It will return True if valid and fill in the second parameter with the number.
Public Class colorCode
Public Function getValue(ByVal itemCode As Integer) As String
Dim codeVal() As Integer = {9999, 3034, 3040, 3035}
Dim colorVal As String = ""
If codeVal.Contains(itemCode) Then
Select Case itemCode
Case 9999
colorVal = "BRILLIANT WHITE EMULSION"
Case 3034
colorVal = "OFF-WHITE EMULSION"
Case 3040
colorVal = "Blue"
Case 3035
colorVal = "Green"
End Select
Else
colorVal = "No matching color"
End If
Return colorVal
End Function
End Class
And in the form...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim itemCode As Integer
If Integer.TryParse(TextBox1.Text, itemCode) Then
Dim colorDesc As colorCode = New colorCode()
TextBox2.Text = colorDesc.getValue(itemCode)
Else
MessageBox.Show("Please enter a valid number")
End If
End Sub
Add the return statement. You should also check the value of itemCodeTextBox.Text to make sure it's a numeric value before you call colorDesc.getValue otherwise your program may crash if a non-numeric value is entered into the textbox
You are missing the "return" part of your method.
Public Function getValue(ByVal itemCode As Integer) As String
That's what it'll take to declare you're returning a string value, and then you actually return your vale at the end of the method.
Next
return colorVal
End Sub
There are other ways to do this as well as better ways to deal with your "getValue" code, but this should get you running for now. The rest of the improvements are likely a different Question, or even series of Questions. Or you could go to the Code Review stack and get more help there.

How can I get specific items from text file? Visual Basic 2010

I am trying to figure out how to get a message box to show only specific words from a text file, which contains all of the words within the dictionary. I have tried various different ways, but cannot get it to work, but I do think I am on the right track so just need some pointers.
Basically, there is a scrambled up string, which is different every time, and is contained within a label. I want the program to only show words which contains the letters inside the scrambled string, but not sure how to achieve this?
Here is the code that I have so far:
Private Sub btnAnswers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnswers.Click
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("C:\Users\Katie\Documents\Project\dictionary.txt"))
Dim Letters As String
Dim OneCharacter As String
Dim Found As Boolean
Dim item As String
Dim AllCharacters As String
Found = False
Letters = lblLetters.Text
For i = 0 To Letters.Length - 1
OneCharacter = Letters.Substring(i, 1)
For Each item In hash
If item.Contains(OneCharacter) Then
Found = True
AllCharacters = OneCharacter
Else
Found = False
End If
MsgBox(item)
Next
Next i
End Sub
The message box does show up words, from the dictionary, but words can contain letters that are not present in the label string, so my code is wrong. Can anyone help? Apologies, but I am new to programming.
With a simple modification to the previous answer you can restrict the output to only words that contain only the scrambled letters:
Private Sub btnAnswers_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("C:\Users\Katie\Documents\Project\dictionary.txt"))
Dim Letters As String = lblLetters.Text
For Each item As String In hash
Dim word As String = item.ToLower()
For i = 0 To Letters.Length - 1
Dim OneCharacter As Char = Char.ToLower(Letters(i))
While word.Contains(OneCharacter)
word = word.Remove(word.IndexOf(OneCharacter), 1)
End While
Next
If (word.Length = 0) Then
'The given dictionary entry includes all the letters in the label. No more iterations will be performed
MsgBox(item)
Exit For
End If
Next
End Sub
With this code if the scrambled letters contain 'bok' then "book" will get selected. However removing the while loop and leaving only the remove statement, will ensure that only the exact number of each different letter will match. so that 'obok' will be needed to match "book".
As suggested by Steven Doggart, you have to invert the loop nesting. What you want is going through all the dictionary entries and, for each of them, checking if it contains all the letters in the string. Your loop structure is not allowing to do that.
I have performed the required updates in your code. Bear in mind that this code ignores caps ("A" is the same than "a").
Private Sub btnAnswers_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("C:\Users\Katie\Documents\Project\dictionary.txt"))
Dim Letters As String = lblLetters.Text
For Each item As String In hash
Dim Found As Boolean = True
For i = 0 To Letters.Length - 1
Dim OneCharacter As String = Letters.Substring(i, 1)
Dim itemToLower As String = item.ToLower()
If Not itemToLower.Contains(OneCharacter.ToLower()) Then
Found = False
Exit For
End If
Next i
If (Found) Then
'The given dictionary entry includes all the letters in the label. No more iterations will be performed
MsgBox(item)
Exit For
End If
Next
End Sub
This code looks for keys containing all the characters in the given label (not at the contrary), that is: with a label "dict", "dictentry" would be right.
In any case, the whole point of my answer is not delivering a code which you just have to execute; the point of this code is helping you to understand what you did wrong and how to start doing things right. If you are not interested in this exact functionality, you woud have to edit my code such that what you want can be accomplished; or, ideally, you would be writing your own code completely from scratch.
You're calling MsgBox(item) outside of the if statement that determines whether the current word contains the current character. Which means it's going to pop up for every letter, every word. Move MsgBox(item) inside the first half of the if statement if you only want it to show when the letter is actually found in the word.
I'd also suggest following Steven Doggart's advice and reversing the way the loops are nested. If the characters are the outer loop, you could get the message box multiple times per word (e.g., if your letters are "sdf" and one of the words is "foods," it will pop up 3 times).
For Each item In hash
For i = 0 To Letters.Length - 1
OneCharacter = Letters.Substring(i, 1)
If item.Contains(OneCharacter) Then
Found = True
AllCharacters = OneCharacter
MsgBox(item)
Else
Found = False
End If
Next
Next

Convert.ToInt16 vb.net

I am using the following code as a learning progress for myself:
Public Class Form1
Private Sub BtnAntwoord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAntwoord.Click
Dim testNummer As Integer
Dim uitkomst As Single
Dim waarde1 As Integer = Convert.ToInt16(txtNummers1)
Dim waarde2 As Integer = Convert.ToInt16(txtNummers2)
uitkomst = (waarde1 * waarde2)
testNummer = Convert.ToString(uitkomst)
MsgBox(testNummer)
End Sub
End Class
What I am trying to accomplish is a small window with 2 textfields and a button wich, when pressed, presents the answer to the question "waarde 1 * waarde2" in a popup window.
When I execute this code, the following error is presented:
InvalidCastException was unhandled
and the line "waarde1 As Integer = Convert.ToInt16(txtNummers1)" is highlited
I am not looking for an answer per se, just the understanding as to why this does not work, seeing as I am extremely new to vb.net and I am trying to expand my knowledge of the language.
if txtNummers1 and txtNummers2 are textboxes then you should write
Dim waarde1 As Short = Convert.ToInt16(txtNummers1.Text)
Dim waarde2 As Short = Convert.ToInt16(txtNummers2.Text)
You can't convert a TextBox type to an Integer type. You convert the Text (a string type) property of a TextBox to an Integer supposing that this property contains in effect a number.
Also, why convert to a 16bit numeric type and then assign the result to a 32bit type?
A better approach is the following
Dim waarde1 As Short
Dim testNum as String = txtNummers1.Text
if Int16.TryParse(testNum, waarde1) Then
Console.WriteLine("It is a 16 bit number " + waarde1.ToString)
else
Console.WriteLine("Not a 16 bit number " + waarde1.ToString)
Here MSDN on TryParse

VB 2010 array/write array to file

I'm close to getting this to work, but currently can't get any output to display in the listbox. I had it working, but needed to move some things around to get the join function to work.
In my program, a user enters input into a textbox and an array is displayed in a listbox based on what they type in. For example, if they type in "a", all foods (in the textfile that is connected to the program) that start with "a" will be displayed.
When there is output, I need to find a way to name this array (which is created based on what the user inputs) and join all of the items in the listbox (example: foods stacked on top of each other in the listbox will be shown at the bottom as a string).
I am posting the code that I have thus far; all of the errors that I'm getting (and potentially my logic errors) are just in the first public class until the end of the first if-next statement:
Public Class frmFoods
Dim foods() As String = IO.File.ReadAllLines("foods.txt")
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
For Each food As String In foods
smallerarray = listfoods(Letter)
lstOutput.Items.Add(Letter)
userarray = Join(smallerarray, ", ")
lstOutput.Items.Add(userarray)
Next
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
Function listfoods(ByVal letter As String) As String()
Dim foodarray(foods.Count - 1) As String
Dim counter As Integer = 0
For Each food As String In foods
If food.StartsWith(letter) Then
foodarray(counter) = food
counter += 1
End If
Next
ReDim Preserve foodarray(counter - 1)
Return foodarray
End Function
you need to save the results of the listfoods function in a dictionary or similar and associate it with a key if you want to 'Name' it, although its not clear why you need to do this
As for listing the foods starting with the particular letter, you just need to iterate your result of the function listfoods and separate each one by a comma don't you?
What you have now will create many lists of each food as you are getting the list of food beginning with a particular letter for each food.. As I understand the question you only need to do that once.
Example:
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
'get all items from the file which begin with the letter the user chose
smallerarray = listfoods(Letter)
'add that letter to the output listbox
lstOutput.Items.Add(Letter)
'join all of the elements which begin with that letter
'into a single comma separated string
userarray = Join(smallerarray, ", ")
'add that string to the output
lstOutput.Items.Add(userarray)
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
it would probably be useful for you to step through the code and see the values of the variable at each place and compare this with what you expect to see if you can see where the actual value differs from what your logically expect so you can start to identify where the issue is