LINQ Query in VB.net comparing integers - vb.net

I am trying to write a LINQ query that compares an integer value in a database to an integer variable. This is not working. I can compare text values but comparing integers returns a null.
Private Sub txtRoomNum_TextChanged(sender As Object, e As EventArgs) Handles txtRoomNum.TextChanged
If Val(txtRoomNum.Text) > 99 Then
Dim intRoomNum As Integer
intRoomNum = Val(txtRoomNum.Text)
Dim RoomData = (From Rooms In BadermanIslandDataSet.Rooms
Where Rooms.HotelID = intHotelID).SingleOrDefault
''Where Rooms.HotelID = intHotelID And Rooms.RoomNumber = intRoomNum
Try
txtTest.Text = RoomData.RoomID
Catch ex As Exception
txtTest.Text = "null"
End Try
End If
End Sub

Change txtTest.Text = RoomData.RoomID
to Convert.ToInt32(txtTest.Text) = RoomData.RoomID)
You were comparing string and integer before

Since it's user input I would try using Integer.TryParse when getting the value from the text field. This will prevent an exception from being raised, and in the case the parse fails you can ask your user to only use a number in that field.
If Integer.TryParse(txtRoomNum.Text, intRoomNum) Then
...your logic
Else
...something to let them know to only put a number in txtRoomNum.Text
End If

Ok, I found the issue. I needed a RoomsBindingSource on the form. Once that was added it worked like a champ.

Related

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.

Filtering binding source

This should be easy but I am having a headbanging of a time trying to get this to work! I have done a search and tried all most EVERY SINGLE ONE. Nothing works. I have a datagrid with a binding source. A user will type text into a textbox and the grid is SUPPOSED to change to only show records that contain what user typed in the name. Simple right? NOPE! Not for me! What am I doing wrong? Code below.
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim Found As Boolean = False
Dim StringToSearch As String = ""
Dim ValueToSearchFor As String = "%" & SearchTextBox.Text.Trim.ToLower & "%"
Dim CurrentRowIndex As Integer = 0
Try
If ReferencesGrid.Rows.Count = 0 Then
CurrentRowIndex = 0
Else
CurrentRowIndex = ReferencesGrid.CurrentRow.Index + 1
End If
If CurrentRowIndex > ReferencesGrid.Rows.Count Then
CurrentRowIndex = ReferencesGrid.Rows.Count - 1
End If
If ReferencesGrid.Rows.Count > 0 Then
For Each gRow As DataGridViewRow In ReferencesGrid.Rows
StringToSearch = gRow.Cells(1).Value.ToString.Trim.ToLower
If InStr(1, StringToSearch, LCase(Trim(SearchTextBox.Text)), vbTextCompare) Then
TrainingItemBindingSource.Filter = String.Format("Name LIKE '{0}'", ValueToSearchFor)
Exit For
End If
Next
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
You should get rid of pretty much all that code. If you want to filter the data then just filter the data. There's no conditional statements required and loops required. Just set the Filter property and any records that don't match the filter will be hidden:
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
TrainingItemBindingSource.Filter = $"Name LIKE '%{SearchTextBox.Text.Trim()}%'"
End Sub
As you can see, it is simple. I've no real idea what you were actually trying to achieve with the rest of that code. That will exclude any records where the Name column does not contain the search text.
Note that there is no need to try to force case-insensitivity by using ToLower or the like. Just like in real SQL, comparisons done this way in a DataTable are case-insensitive by default. You have to explicitly set the CaseSensitive property of the DataTable or its parent DataSet to True to make such comparisons case-sensitive.
I should also point out that the ability to filter is predicated on the data source implementing certain interfaces. If the data source is a DataTable then you have those interfaces for free. If you have actually bound to something else, e.g. a List(Of T), then you won't be able to filter this way because the required members do not exist.

input validation in vb 2013 input box string conversion error

My program crashes when I enter letter characters into the input box or leave the input box blank. Why is my validation if statement not working?
Option Strict On
Public Class frmPickUpSticks
Dim playersTurn As Boolean = False
Dim remainingSticks As Integer 'count sticks
Dim losses As Integer = 0 'count player losses
Private Sub btnNewGame_Click(sender As Object, e As EventArgs) Handles btnNewGame.Click
lblOutput.Text = ""
remainingSticks = CInt(InputBox("How many matchsticks would you like (5 - 25)?", "Pick Number of Matches!"))
'Validate input
If IsNumeric(remainingSticks) Then
If (remainingSticks >= 5) And (remainingSticks <= 25) Then
DisplayMatches()
If (remainingSticks Mod 4 = 1) Then
MessageBox.Show("You go first!")
playersTurn = True
turns()
Else
MessageBox.Show("I go first.")
turns()
End If
Else
MessageBox.Show("Please enter a number between 5 and 25.")
End If
Else
MessageBox.Show("Input must be numeric.", "Input Error")
End If
You can't automatically take what your user types in an InputBox and pass this input to any function or method that expects a number for input. The InputBox method has been designed to return a string and this string need to be converted but you need to use methods that know how to parse a string. Otherwise methods that are not designed to handle nonnumeric values (CInt) will cause exceptions.
Instead you should try some kind of parsing and the NET Library offers many tools to use. In your case the correct one is Int32.TryParse
Dim remainingSticks As Integer
Dim userInput = InputBox("How many matchsticks .....")
If Int32.TryParse(userInput, remainingSticks) Then
.... ok your remainingStick contains the converted value
Else
MessageBox.Show("You should type a valid integer number between 5-25")
The Int32.TryParse will look at your input string and try to convert to a valid integer value. If it succeed then the second parameter contains the converted integer and returns True, if it fails it return false and your second parameter will have the default value of zero.
Of course after a succesfull conversion to an integer your don't need anymore a check with IsNumeric
You should use a string variable in the inputbox
dim st as string
st = InputBox("How many matchsticks would you like (5 - 25)?", "Pick Number of Matches!"))
remainingSticks = val(st)
. . .

VB.net Using a string to change something.Text

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

VB.NET AlphaNumeric into integer

If Textbox1.text contains a string value of ZU4, how can I convert that string to it's numeric ASCII codes, and output it to a second text box?
I'd like to do this using a FOR LOOP conditional statement which will read every character in INPUT?
Sample:
INPUT Textbox1.Text = ZU4
OUTPUT Textbox2.Text = 908552
You could also use LINQ:
TextBox2.Text = String.Join(String.Empty, From c In Textbox1.Text.ToCharArray Select (Asc(c).ToString))
Could be useful on some job interviews... :)
All of the other answers will work with your given example, however, some of the suggestions are using unicode encoding rather than ASCII. If strictly adhering to ASCII encoding is important, then you should explicitly specify the encoding that you want to use.
Convert.ToInt32 uses UTF-16 encoding. I'm not sure what CInt will do, but I suspect it works the same way. Using Asc is better, but it is still dependent on the code page setting for the thread, so it's still not entirely safe. Besides that, Asc is an old VB6 function which is provided in VB.NET, primarily for backwards compatibility.
Therefore, I would recommend using the ASCIIEncoding class instead. You can get an instance of that class using the shared ASCII property of the Encoding class in the System.Text namespace, for instance:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
builder.Append(b.ToString())
Next
Return builder.ToString()
End Function
Then, you can call the function like this:
Textbox2.Text = ConvertTextToAsciiDigits(Textbox1.Text)
However, I can't imagine that the resulting string will be usable unless every character results in a two digit number. Therefore, I would force it to be two digits by doing something like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException() ' Throws an exception if the value is three digits
End If
builder.Append(b.ToString("00")) ' Adds a leading zero to one-digit values
Next
Return builder.ToString()
End Function
To add a hyphen after every fourth digit, as you mentioned in a comment below, you could just keep track of the total digits added since the last hyphen, like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
Dim digitsSinceHyphen As Integer = 0
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException()
End If
builder.Append(b.ToString("00"))
digitsSinceHyphen += 2
If digitsSinceHyphen >= 4 Then
builder.Append("-")
digitsSinceHyphen = 0
End If
Next
Return builder.ToString()
End Function
Here is one approach, in C#:
Textbox2.Text = string.Empty;
foreach(var c in Textbox1.Text)
{
Textbox2.Text += ((int)c).ToString();
}
VB.NET:
Textbox2.Text = String.Empty
For Each c As Char In Textbox1.Text
Textbox2.Text = Textbox2.Text + Convert.ToInt32(c).ToString()
Next
It:
Clears out Textbox2.Text
Loops over each character in the input
Concatenates the integer value output as a string to the output text
TextBox2.Text = ""
For i As Integer = 0 To TextBox1.TextLength - 1
TextBox2.Text += Asc(TextBox1.Text(i)).ToString()
Next
i modified the code from this Link
Function AsciiEncode(ByVal value As String) As String
Dim encValue As New System.Text.StringBuilder(value.Length * 6)
Dim c As Char
For Each c In value
encValue.Append(Convert.ToInt32(c))
Next
Return encValue.ToString()
End Function
usage:
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
TextBox2.Text = AsciiEncode(TextBox1.Text)
End Sub