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
Related
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.
Why do I keep getting two input boxes instead of one? What am I doing wrong? Is it how I am passing values through functions? If so, how can I fix this?
Private Sub Calculate_Click(sender As Object, e As EventArgs) Handles Calculate.Click
'Dim ready_ship As Integer = GetInStock()
Dim display_spools As Integer = ReadyToShip()
Dim display_backOrders As Integer = BackOrdered()
lbl_rship.Text = display_spools.ToString()
lbl_backo.Text = display_backOrders.ToString()
End Sub
Function GetInStock() As Integer
Dim amount_Spools As String = Nothing
amount_Spools = InputBox(" Enter the number of spools currently in stock: ")
Return CInt(amount_Spools)
End Function
Function ReadyToShip() As Integer
Dim ready_ship As Integer = GetInStock()
Dim a As Integer
a = CInt(ready_ship)
Return a
End Function
Function BackOrdered() As Integer
Dim b As Integer = ReadyToShip()
Dim c As Integer
c = b - CInt(TextBox1.Text)
Return c
End Function
End Class
Your Calculate_Click event is calling ReadyToShip() and BackOrdered() functions which are both going to GetInStock() function, which is displaying the input box. So it will be displayed twice.
This class would be better served using properties, they are easier to manage and will help avoid this kind of method duplication.
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
Working with Visual Basic in Visual Studio 2013. I need to take input from a textbox on form1 and use it as an integer in functions of a module. When I call one of the functions on form1 after a click event, I get an error for invalid arguments on the public function integers. How can I get the text passed to the module and then treated as an integer?
This is what I have on form1. This worked okay on the last project, which required the calculations to be performed and displayed only on form1. This project requires calculations to be performed in a module I created, and then displayed in labels on form2. (I'm still very new to this).
'Define inputs as public variables
Public intNumber1 As Integer
Public intNumber2 As Integer
'Create Function to validate inputs as integers
Public Function ValidateInputFields() As Boolean
'Try to convert each input to integer. If not, return error message, clear input, and return focus
If Not Integer.TryParse(txtNumber1.Text, intNumber1) Then
MessageBox.Show("Please enter only whole numbers.")
txtNumber1.Clear()
txtNumber1.Focus()
Return False
End If
If Not Integer.TryParse(txtNumber2.Text, intNumber2) Then
MessageBox.Show("Please enter only whole numbers.")
txtNumber2.Clear()
txtNumber2.Focus()
Return False
End If
Return True
End Function
This is the error message I get:
Error 1 Argument not specified for parameter 'intNumber1' of 'Public
Function AddInt() As Integer'.
This is the function I've written in the module:
'Create function to pass the values and add
Public Function AddInt(ByVal intNumber1 As Integer, intNumber2 As
Integer) As Integer
'Define intSum
Dim intSum As Integer
'AddInt adds numbers 1 and 2
intSum = intNumber1 + intNumber2
'Return the result
Return intSum
End Function
Text from a TextBox will be of type String and you need to convert it to an integer after checking whether its content can be safely interpreted as a number.
Something like this :
Dim num As Integer
If Not Integer.TryParse(TextBox1.Text, num) Then
'... it's not an integer, so don't try to use it
Else
'... call method using "num" as your integer parameter
End If
This is how I finally got my function calls to work correctly:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles
btnAdd.Click
'create instance for results form and define sum variable
Dim frmResults As New Results
Dim intSum As Integer
'If inputs are valid, display the integer sum on results form
If ValidateInputFields() Then
'Call Add Integer function from module
intSum = AddInt(intNumber1, intNumber2)
'Send answers to Results form and display
frmResults.lblNumber1Result.Text = intNumber1.ToString()
frmResults.lblOperatorResult.Text = "plus"
frmResults.lblNumber2Result.Text = intNumber2.ToString()
frmResults.lblEqualsResult.Text = intSum.ToString()
frmResults.ShowDialog()
End If
Everything worked once I added the (intNumber1, intNumber2) right after the function call of AddInt.
The ValidateInputFields() function is the TryParse method that #mcrimes was helping me with earlier. This did handle any non-numeric inputs or blanks left as it did in my previous project.
Thanks again #Jonathan and #mcrimes for all of your help.
I am getting the error "Format Exception was unhandled at "Do While objectReader.Peek <> -1
" and after. any help would be wonderful.
'Date: Class 03/20/2010
'Program Purpose: When code is executed data will be pulled from a text file
'that contains the named storms to find the average number of storms during the time
'period chosen by the user and to find the most active year. between the range of
'years 1990 and 2008
Option Strict On
Public Class frmHurricane
Private _intNumberOfHuricanes As Integer = 5
Public Shared _intSizeOfArray As Integer = 7
Public Shared _strHuricaneList(_intSizeOfArray) As String
Private _strID(_intSizeOfArray) As String
Private _decYears(_intSizeOfArray) As Decimal
Private _decFinal(_intSizeOfArray) As Decimal
Private _intNumber(_intSizeOfArray) As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'The frmHurricane load event reads the Hurricane text file and
'fill the combotBox object with the data.
'Initialize an instance of the StreamReader Object and declare variable page 675 on the book
Dim objectReader As IO.StreamReader
Dim strLocationAndNameOfFile As String = "C:\huricanes.txt"
Dim intCount As Integer = 0
Dim intFill As Integer
Dim strFileError As String = "The file is not available. Please restart application when available"
'This is where we code the file if it exist.
If IO.File.Exists(strLocationAndNameOfFile) Then
objectReader = IO.File.OpenText(strLocationAndNameOfFile)
'Read the file line by line until the file is complete
Do While objectReader.Peek <> -1
**_strHuricaneList(intCount) = objectReader.ReadLine()
_strID(intCount) = objectReader.ReadLine()
_decYears(intCount) = Convert.ToDecimal(objectReader.ReadLine())
_intNumber(intCount) = Convert.ToInt32(objectReader.ReadLine())
intCount += 1**
Loop
objectReader.Close()
'With any luck the data will go to the Data Box
For intFill = 0 To (_strID.Length - 1)
Me.cboByYear.Items.Add(_strID(intFill))
Next
Else
MsgBox(strFileError, , "Error")
Me.Close()
End If
End Sub
Put a break-point on these lines and step through your code:
_decYears(intCount) = Convert.ToDecimal(objectReader.ReadLine())
_intNumber(intCount) = Convert.ToInt32(objectReader.ReadLine())
Whatever is being returned by ReadLine isn't in the proper decimal or integer format when passed to the converters. You'll need to add some try/catch blocks around the do-while loop operations to handle it gracefully and make sure your data is formatted the way you expected since the wrong parts are being used in this scenario.
Also, each call to ReadLine is returning an entirely new line and the Peek check won't account for those. As long as you can trust your data that's fine.
Instead of using Convert.ToDecimal an Convert.ToInt32, try using Decimal.TryParse() and Int32.TryParse(). If they don't parse, you know your file isn't setup correctly. If they do parse, then you've loaded the value into a variable for your use.
EDIT:
Use it like this.
Dim myDecimal As Decimal
If Decimal.TryParse(objectReader.ReadLine(), myDecimal) Then
'your string successfully parsed. Use myDecimal however you want. It has the parsed value.
Else
'your string is not a decimal. Now that you know that, you can handle this situation here without having to catch an exception.
End If