How do you check if an input is a negative number in VB - vb.net

I am trying to do some validation which checks if the value in a textbox is an integer then checks if the the value is negative. It correctly checks if the value is an integer but I can't get it to check if the value is negative.
Note: The value being entered is the number of competitions attended so comps = competition etc...
Dim comps As Integer
Dim value As Double
If Integer.TryParse(txtCompsEntered.Text, integer) Then
value = txtCompsEntered.Text
If value < 0 Then
lblcompsatten.ForeColor = Color.Red
txtCompsEntered.ForeColor = Color.Red
lblcompsatten.Text = "No negative numbers"
Else
lblcompsatten.ForeColor = Color.Black
txtCompsEntered.ForeColor = Color.Black
lblcompsatten.Text = ""
End If
lblcompsatten.ForeColor = Color.Black
txtCompsEntered.ForeColor = Color.Black
lblcompsatten.Text = ""
Else
lblcompsatten.ForeColor = Color.Red
txtCompsEntered.ForeColor = Color.Red
lblcompsatten.Text = "Not a number"
End If
I have already looked at this thread but it didn't seem to work
how-to-check-for-negative-values-in-text-box-in-vb

Tryparse will convert the input to an integer if it succeeds - you don't need both the comps and value variables. Here's an example of how it works:
Dim comps As Integer
Dim input As String = "im not an integer"
Dim input2 As String = "2"
'tryparse fails, doesn't get into comps < 0 comparison
If Integer.TryParse(input, comps) Then
If comps < 0 Then
'do something
End If
Else
'I'm not an integer!
End If
'tryparse works, goes into comps < 0 comparison
If Integer.TryParse(input2, comps) Then
If comps < 0 Then
'do something
End If
End If

There are a couple of things off with your code but the main issue is using Integer.TryParse incorrectly.
Incorrect:
Dim value As Double
If Integer.TryParse(txtCompsEntered.Text, integer) Then
value = txtCompsEntered.Text
If value < 0 Then
Correct:
Dim value As Integer
If Integer.TryParse(txtCompsEntered.Text, value) Then
If value < 0 Then
The things to note are that Integer.TryParse will return a boolean value (true if the value can be convertan integer, false if not). It will them dump the converted value into the second parameter you pass into it. In your case, you had 'integer', which is incorrect. You should be passing in a variable and then using that variable for your comparison.
Also, be careful with your types. You have 'value' as a double when you seem to be working with integers.

Maybe try this?
If myinteger.toString.Contains("-") Then
'it's negative
Else
'it isn't
End If
Or even simplier
If myinteger < 0 Then
'it's not negative
Else
'it is negative
End if

Related

How can i allow only positive number in my code

I'm still new in VB and I have emailed my lecturer but it seems like he is quite busy and didn't have time to reply to me. Can anyone teach me with it?
Dim split = InputTextBox.Text.Split(vbNewLine)
Dim check As Boolean
For i = 0 To split.Length - 1
check = IsNumeric(split(i))
If Not check Then
Exit For
End If
Next
If check Then
FootForm.Show()
Else
MessageBox.Show("Please enter in positive number only")
End If
I am not sure how your value is stored in the form control. The below should help
Dim split as String = InputTextBox.Text.Split(vbNewLine)
Dim parsedint as Integer
If Int32.TryParse(split, parsedint) AndAlso parsedint < 0 Then
MessageBox.Show("Please enter in positive number only")
Else
FootForm.Show()
End If
You can throw a bit of LINQ at the problem:
If InputTextBox.Lines.All(Function(s)
Dim n As Double
Return Double.TryParse(s, n) AndAlso n >= 0.0
End Function) Then
'All lines represent non-negative numbers.
End If
The longhand version would be:
Dim result = True
For Each s In InputTextBox.Lines
Dim n As Double
If Not Double.TryParse(s, n) OrElse n < 0.0 Then
result = False
Exit For
End If
Next
If result Then
'All lines represent non-negative numbers.
End If

A better way in checking if datagridview contains integer?

So currently I have a datagridview and i'm importing an excel file into it. Columns 3-6 should contain numbers.
This is my code as of now .. but there has to be a quicker and more efficient way of checking for number?
maybe something with isinteger..
Also this only checks for one column..
the isFound variable is a bool to check if a certain string is in the imported excel file.
so for example, if the excel file contains the word "data" in a certain cell, it would in turn mark isFound = true.
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.Cells("F3").Value Is DBNull.Value Then
If (isFound) Then
'MessageBox.Show("Data Exists!")
Select Case row.Cells("F3").Value
'checks for all numbers 0 - 9999
Case "1", "2", "3", "4", "5", "6" .. "9999"
'All pass verification, Do nothing
Case Else
'Point out the wrong value
row.Cells("F3").Style.BackColor = Color.Red
End Select
Else
' MessageBox.Show("Not a number!")
End If
End If
Next
You can use Integer.TryParse. It takes a string and a number. If it can convert it properly, it returns true and put the value inside the number variable.
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.Cells("F3").Value Is DBNull.Value Then
If (isFound) Then
Dim cellNumber As Integer
If Integer.TryParse(row.Cells("F3").Value, cellNumber) AndAlso cellNumber >= 0 AndAlso cellNumber <= 9999 Then
'All pass verification, Do nothing
Else
'Point out the wrong value
row.Cells("F3").Style.BackColor = Color.Red
End If
Else
' MessageBox.Show("Not a number!")
End If
End If
Next
An other idea would be to create a function that does all the check and just call that function instead.
Private Function IsInRange(ByVal numberAsString As String, ByVal min As Integer, ByVal max As Integer) As Boolean
Dim number As Integer
If Not Integer.Parse(numberAsString, number) Then
Return False
End If
If number < min Or number > max Then
Return False
End If
Return True
End Function
...
If IsInRange(row.Cells("F3").Value, 0, 9999) Then
'All pass verification, Do nothing
Else
'Point out the wrong value
row.Cells("F3").Style.BackColor = Color.Red
End If
This solution isn't perfect but still better... I could have used IsNumeric, but this allows doubles. You could use IsNumeric andalso cint(cdbl(s))=cdlb(s)
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.Cells("F3").Value Is DBNull.Value Then
If (isFound) Then
'MessageBox.Show("Data Exists!")
dim s as string = row.Cells("F3").Value
for i as integer = 0 to 9
s= strings.replace(s,cstr(i),"")
next
if strings.len( row.Cells("F3").Value)<=4 andalso s="" then
'it IS an integer <=9999
Else
'Point out the wrong value
row.Cells("F3").Style.BackColor = Color.Red
Else
' MessageBox.Show("Not a number!")
End If
Next
edited:
alternative:
dim s as string = row.Cells("F3").Value
if isnumeric(s) andalso cdbl(s)=cint(cdbl(s)) andalso cint(s)<=9999 then
'it IS an integer <=9999

Conditional formatting of DataGridView cell data - Change color on negative

I was hoping to be able to use color based conditional formatting in the DefaultCellStyle.Format field for DataGridView cells, in a similar way to how Excel handles this.
For example in Excel, a format string of £#,##0.00;[Red]-£#,##0.00 will display negative values in red.
Is this supported in VB.NET ?
I am aware I can use the .CellFormatting event to conditionally change cell text color but was looking for a less bulky and restrictive way of doing this.
By creating the following CellFormatting addition, I am able to use Excel style conditional colour formatting in the cells format field. Setting the colour for negative/positive/zero values is supported.
Format string is expected to be in the following format (all colours optional) :
[colour]<format for +value> ; [colour]<format for -value> ; [colour]<format for zero value>
..a test DGV column with conditional formatting
c = New DataGridViewColumn
c.Name = "AmountOUT"
c.DataPropertyName = c.Name
c.HeaderText = "AmountOUT"
c.CellTemplate = New DataGridViewTextBoxCell
c.DefaultCellStyle.Format = "[Green]£0.00;[Red]-£0.00;[Blue]zero"
.Columns.Add(c)
..
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
'Split format string to positive / negative / zero components
Dim posnegzero As List(Of String)
posnegzero = e.CellStyle.Format.Split(CChar(";")).ToList
Dim coloursPNZ As New List(Of String)
Dim remainderformatPNZ As String = ""
For Each s As String In posnegzero
If s.Contains("[") And s.Contains("]") Then
'Extract [xxx] contents
coloursPNZ.Add(s.Substring(s.IndexOf("[") + 1, s.IndexOf("]") - s.IndexOf("[") - 1))
'Append rebuilt format excluding [xxx]
remainderformatPNZ &= s.Substring(0, s.IndexOf("[")) & s.Substring(s.IndexOf("]") + 1, s.Length - s.IndexOf("]") - 1) & ";"
Else
coloursPNZ.Add("")
remainderformatPNZ &= s & ";"
End If
Next
'Set format excluding any [xxx] components
e.CellStyle.Format = remainderformatPNZ
'Check for positive value
If Val(e.Value) > 0 And coloursPNZ.Count >= 1 Then
If coloursPNZ(0) <> "" Then
e.CellStyle.ForeColor = Color.FromName(coloursPNZ(0))
End If
End If
'Check for negative value
If Val(e.Value) < 0 And coloursPNZ.Count >= 2 Then
If coloursPNZ(1) <> "" Then
e.CellStyle.ForeColor = Color.FromName(coloursPNZ(1))
End If
End If
'Check for zero value
If Val(e.Value) = 0 And coloursPNZ.Count >= 3 Then
If coloursPNZ(2) <> "" Then
e.CellStyle.ForeColor = Color.FromName(coloursPNZ(2))
End If
End If
End Sub
Dim dgv As DataGridView = Me.DataGridView1
For i As Integer = 0 To dgv.Rows.Count - 1
For ColNo As Integer = 4 To 7 ' number columns
If Not dgv.Rows(i).Cells(ColNo).Value < 0 Then
dgv.Rows(i).Cells(ColNo).Style.BackColor = vbcolor.Red
End If
Next
Next
checking for negative values lookout for strings format and check accordingly
Tryparse will convert the input to an integer if it succeeds - you don't need both the comps and value variables. Here's an example of how it works:
Dim comps As Integer
Dim input As String = "im not an integer"
Dim input2 As String = "2"
'tryparse fails, doesn't get into comps < 0 comparison
If Integer.TryParse(input, comps) Then
If comps < 0 Then
'do something
End If
Else
'I'm not an integer!
End If
'tryparse works, goes into comps < 0 comparison
If Integer.TryParse(input2, comps) Then
If comps < 0 Then
'do something
End If
End If

Function 'DisplayArray' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used

I keep getting a error and because of this my code wont work. The error is "Function 'DisplayArray' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used". I can't get rid of this error. I'm new to programming, can anyone help?
Private Function DisplayArray() As String
Dim j As Integer = 0
ReDim Preserve Array(UpperSub)
Dim AddNum As Double = 0.0
txtAddNum.Focus()
If Double.TryParse(txtAddNum.Text, AddNum) Then
If AddNum > 100 Then
MessageBox.Show("Number must be below 100")
ElseIf AddNum < 0 Then
MessageBox.Show("Number must be above 0")
Else
Array(UpperSub) = CDec(AddNum)
UpperSub = UpperSub + 1
End If
Else
MessageBox.Show("Value has to be a number")
End If
txtAddNum.Clear()
txtDisplay.Clear()
For j = 0 To UpperSub - 1
txtDisplay.Text = txtDisplay.Text _
& CStr(Array(j)) & ControlChars.NewLine
Next
txtNumberOfScores.Text = CStr(UpperSub)
End Function
A Function is designed to return a result, using the Return keyword. Your Function does not have a Return statement. Since none of the possible code paths (determined by branching on the If statements as well as the flow from beginning to end) return a value, you're getting this part of the error message: "Function 'DisplayArray' doesn't return a value on all code paths."
The second part of the error message means that if you tried to assign the return value of the Function to a variable, like this:
Dim result As String = DisplayArray()
You'd get a null value, as nothing is returned from the function.
The simplest solution is to change from a Function to a Sub. Subs in VB.NET do not return a value. So change
Private Function DisplayArray() As String
To
Private Sub DisplayArray()
And
End Function
To
End Sub
Note that the As String() in the Function declaration says this method will return a value that is a String, and the Sub has no return value (again, because it doesn't return a value).
To make this a Function that returns a value, you'll have to return at least one value from the method. Here's an example:
Private Function DisplayArray() As String
Dim j As Integer = 0
ReDim Preserve Array(UpperSub)
Dim AddNum As Double = 0.0
txtAddNum.Focus()
If Double.TryParse(txtAddNum.Text, AddNum) Then
If AddNum > 100 Then
MessageBox.Show("Number must be below 100")
Return String.Empty
ElseIf AddNum < 0 Then
MessageBox.Show("Number must be above 0")
Return String.Empty
Else
Array(UpperSub) = CDec(AddNum)
UpperSub = UpperSub + 1
txtAddNum.Clear()
txtDisplay.Clear()
For j = 0 To UpperSub - 1
txtDisplay.Text = txtDisplay.Text _
& CStr(Array(j)) & ControlChars.NewLine
Next
Return CStr(UpperSub)
End If
Else
MessageBox.Show("Value has to be a number")
Return String.Empty
End If
End Function
Essentially, if the validation fails, an empty string is returned. If the validation passes, the rest of the code is executed and the string value of UpperSub is returned.
You could then assign it to the TextBox like this:
txtNumberOfScores.Text = DisplayArray()
The above is a simple example based on your posted code, intended to show you how to return values from a Function. Adjust it to fit your needs (or use a Sub instead). Given that you want to update the display of the txtDisplay with the array and txtNumberOfScores as well you should do fine with a Sub.

multiple validation in vb.net [ non 0 and numeric only]

How can I multi validate a text box? I only want the user to input integer but the integer shouldn't be 0 or less, how can I do this? This is what I've done:
If Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
If IsNumeric(txtCopies.Text) = False Then
ErrorProvider1.SetError(txtCopies, "Number only")
Else
blabla
End If
End If
If IsNumeric(txtCopies.Text) = True AND CINT(txtCopies.Text) >= 0 Then
'Validation Passed
Else
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
End If
there you go, else please explain better
you can also do
If IsNumeric(txtCopies.Text) = True AND CINT(txtCopies.Text) >= 0 Then
'Validation Passed
Else
if not(IsNumeric(txtCopies.Text) = True) then
ErrorProvider1.SetError(txtCopies, "Numbers Only")
else
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
end if
End If
It's been a long time since I've done VB but here you go:
It has to be able to convert whatever is in the text box to an integer.
to do this, it checks if the string is numeric, if it is, then the num variable takes its value (so it can be checked). If this value is greater than 0 then it says it's not valid.
It needs to be a nested If statement for this to happen.
Sub OnClick()
Dim str As String
Dim num As Integer
str = TextBox1.Text
If IsNumeric(str) Then
num = str
If num <= 0 Then
TextBox1.Text = "Sorry, not valid"
End If
Else
TextBox1.Text = "Sorry, not a number"
End If
End Sub
Dim intValue As Integer
If Not Integer.TryParse(TxtBox.Text, intValue) OrElse intValue < 0 Then
Else
End If
In your style ..
If Not IsNumeric(txtCopies.Text) And Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number only")
Else
If Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
Else
'Blabla
End If
End If
If interger. Parse(hours Text box. Tex)<=10 then
' code to perform calculation
Else
Message box.Show("Two many hours."," Invalid Data",MessageBoxButtons.OK)
End if