Ternary operation in VB.Net - vb.net

I am using VB.Net with Visual Studio 2019
Public Shared intDbEnvironment As Integer = CInt(Command().Split(" ")(0))
Sometimes if no parameter is passed, the app crashes. Is there a ternary operator or something that I could use that sets the value to anything if its Nothing or "" or not a number
I've tried
Public Shared intDbEnvironment As Integer = Int32.Parse((Command().Split(" ")(0)))
TryParse Code
Dim success As Boolean = Int32.TryParse((Command().Split(" ")(0)), intDbEnvironment)

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim i As Integer
Integer.TryParse(TextBox1.Text, i)
Debug.Print(i.ToString)
End Sub
If I enter a non integer in the text box - Guess what! I get 0. Because the Function will not attempt to add a value to i if it is not an integer. The default value of and Integer is 0 so that is the value from the declare.

Related

implicit conversion from double to string vb.net

I try to run this code but iget the message implicit conversion from double to string vb.net i try different conversion but its the same
Private Sub TxtRemise_TextChanged(sender As Object, e As EventArgs) Handles TxtRemise.TextChanged
Dim TotalTTc As Decimal
TotalTTc = CDec(TotalHT.Text) + CDec(TXTMontantTva.Text)
TxtTTC.Clear()
TxtTTC.Text = TotalTTc) - val(TxtRemise.Text)
End Sub
You perform a mathematical operation, which will obviously result in a number, and you then assign that to the Text property of a TextBox, which is type String. If you want to assign to a String property then you need to assign a String. If you have a number, that means calling ToString on it.
I checked your code. There was some little mistakes. Check my example and comment if you had the solution to your question, thank you.
Public Class Form1
Private Sub TxtRemise_TextChanged(sender As Object, e As EventArgs) Handles TxtRemise.TextChanged
Dim TotalTTc As Decimal
TotalTTc = CDec(TotalHT.Text) + CDec(TXTMontantTva.Text)
TxtTTC.Clear()
TxtTTC.Text = (TotalTTc - CDec(TxtRemise.Text)).ToString
End Sub
End Class

Confused As To Why This Function Does Not Call?

I'm trying to call this function into a procedure and am confused on why this is not working, I've looked up how to format a function call and don't understand my mistakes.
Structure Stock
Dim category As String
Dim price As Integer
Dim size As String
Dim sku As String
Dim color As String
End Structure
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim stockArray() As String =
IO.File.ReadAllLines("stockInventory.txt")
End Sub
Private Sub btnNewSave_Click(sender As Object, e As EventArgs) Handles btnNewSave.Click
Dim answer
answer = check(sku, stockArray)
End Sub
Function check(sku, stockArray) As Boolean
Dim flag As Boolean
Dim numVar = -1
numVar = Array.IndexOf(stockArray, txtSKU.Text)
If numVar = -1 Then
flag = False
End If
If numVar <> -1 Then
flag = True
End If
Return flag
End Function
It gives me an error saying,
sku is not declared. It may be inaccessible due to its protection
level
I have a structure where sku is defined as being a string. Do I have to declare it again in this sub for it to work?
You can fine-tune this code a bit:
Function check(ByVal stockArray as String()) As Boolean
Return Array.IndexOf(stockArray, txtSKU.Text) >= 0
End Function
It'll return if the element is in the Array.
If your file is very very large and you are doing many searches, I recommend storing in a HashSet instead of an array to get O(1) searching, instead of the O(n) you are getting.
I notice your stock array, has to be declared at the class level, not the method level, to be accessible by other methods.

How to use IO.File.WriteAllLines(FileName, OutputArray) in VB

When using this code in VB I get the error:
System.InvalidCastException: 'Unable to cast object of type 'System.Collections.ArrayList' to type 'System.Collections.Generic.IEnumerable`1[System.String]'.'
Can someone please give me the correct usage?
Full code:
Public Class Form1
Dim OutputArray As New ArrayList
Dim i = 0
Dim Registrationdata
Dim FileName As String = Application.StartupPath & "\Output.txt"
Private Sub IssueTicket_Click(sender As Object, e As EventArgs) Handles IssueTicket.Click
Dim Speed As Integer
If Integer.TryParse(Speedbox.Text(), Speed) Then
If Speed <= 20 Or Speed > 300 Then
MessageBox.Show("Please enter a valid speed between 20-200")
ElseIf Registrationbox.Text() = Nothing Or Not Registrationbox.Text() Like "???? ???" Then
MessageBox.Show("Please enter a vaild registration to continue e.g '1234 123'.")
ElseIf Not IDBox.Text().StartsWith("9") Or Not IDBox.TextLength = 6 Or Not IsNumeric(IDBox.Text()) Then
MessageBox.Show("Please enter a valid OfficerID starting with '9' and is 6 numbers long.")
Else
OutputArray.Add(Speed)
OutputArray.Add(Registrationbox.Text())
OutputArray.Add(IDBox.Text())
MessageBox.Show("Ticket saved")
i += 1
End If
End If
End Sub
Private Sub SaveToFile_Click(sender As Object, e As EventArgs) Handles SaveToFile.Click
Registrationbox.Text() = Registrationdata
IO.File.WriteAllLines(FileName, OutputArray)
End Sub
End Class
To solve your problem quickly you could change your code to:
Dim OutputArray As New List(Of String)
...
OutputArray.Add(Speed.ToString())
OutputArray.Add(Registrationbox.Text())
OutputArray.Add(IDBox.Text())
Problem with your code is that ArrayList doesn't implement an IEnumerable interface, while List does and so File.WriteAllText works; but List(Of String) wants all the items to be of type string, so you have to convert your int to string before pushing it into the list.

the function does not seem to change value when called upon 3 times

I am writing code in visual basic. the goal of the program is to get a function to randomly pick a string from a array when called upon. the problem is it is not choosing a different value when the button calls it to do so. I have no idea why it is doing this.
Also anyone know how to get multlines to print in a label or text? here is my code.
Public Class lbl
Public Function Noun() As String
Dim rand As New Random
Dim index As Integer
Dim nouns() As String = {"boy", "girl", "dog", "town", "car"}
Dim sentence As String ' used to build a sentence
index = rand.Next(5)
sentence = nouns(index)
Return sentence
End Function
Public Function outs(ByVal n1 As String) As String
Dim result = n1
Return result
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
lblRandom.Text = outs(Noun()) & outs(Noun())
lblRandom1.Text = outs(Noun())
End Sub
Public Shared Function RandomNumber(ByVal lowerBound As Integer, ByVal upperBound As Integer) As Integer
Return CInt(Math.Floor((upperBound - lowerBound + 1) * Rnd())) + lowerBound
End Function
Public Function Noun() As String
Dim rand As New Random
Dim index As Integer = -1
Dim nouns() As String = {"boy", "girl", "dog", "town", "car"}
Dim sentence As String ' used to build a sentence
index = RandomNumber(0, 4)
sentence = nouns(index)
Return sentence
End Function
Public Function outs(ByVal n1 As String) As String
Dim result = n1
Return result
End Function
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
lblRandom.Text = outs(Noun()) & outs(Noun())
lblRandom1.Text = outs(Noun())
End Sub
The problem is that you re-create a new random generator each time the Noun() function is called. The random number generator should be a global variable.
The problem is that the .NET random number generator generates random numbers based on a seed. The seed is an integer based on the current system date and time. If you call the random number generator a number of times in quick succession, the same seed is likely to be used and the same "random" number will be generated. The solution is to declare the Random object outside of the procedure in which you wish to generate the random number and to pass a seed to its constructor which is built from the current (random) date and time.
To answer your other questions. Label controls will automatically wrap text if the text contains carriage returns. I have added a carriage return below for lblRandom.
To wrap text in a text box, set its Multiline property to True.
The code that #Aly El-Haddad posted will also work but it contains some VB6 legacy code. I have tried to keep it as .NET as possible. I have also eliminated the superfluous "outs" procedure and made it flexible so that you can add or delete elements in the "nouns" array. Note that with the line "index = rand.Next(5)", you are including element 5 of the array which doesn't exist. The upper bound of the zero-based array is 4 so an "Index was outside the bounds of the array" error will be thrown when your random number generator returns 5.
Private myRandom As New Random(CType(DateTime.Now.Ticks Mod Int32.MaxValue, Integer))
Private Function Noun() As String
Dim index As Integer
Dim nouns() As String = {"boy", "girl", "dog", "town", "car"}
index = myRandom.Next(nouns.GetLowerBound(0), nouns.GetUpperBound(0))
Return nouns(index)
End Function
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
lblRandom.Text = Noun() & Constants.vbNewLine & Noun()
lblRandom1.Text = Noun()
End Sub

Search from a list of string() in VB.NET

I am trying to find if mylines() contains a value or not. I can get the value by mylines.Contains method:
Dim mylines() As String = IO.File.ReadAllLines(mypath)
If mylines.Contains("food") Then
MsgBox("Value Exist")
End If
But the problem is that I want to check if mylines() contains a line which starts with my value. I can get this value from a single line by mylines(0).StartsWith method. But how do I find a string from all the lines which is starting from some value, e.g. "mysearch" and then get that line number?
I am using a for loop to do so, but it is slow.
For Each line In mylines
If line.StartsWith("food") Then MsgBox(line)
Next
Constrained to code for .NET 2.0, please.
Here's one way with Framework 2.0 code, simply set SearchString with the the string you want to search for:
Imports System.IO
Public Class Form1
Dim SearchString As String = ""
Dim Test() As String = File.ReadAllLines("Test.txt")
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
SearchString = "Food"
End Sub
Private Function StartsWith(s As String) As Boolean
Return s.StartsWith(SearchString)
End Function
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim SubTest() As String = Array.FindAll(Test, AddressOf StartsWith)
ListBox1.Items.AddRange(SubTest)
End Sub
End Class
When I test this with a file with 87,000 lines, it takes about .5 sec, to fill the listbox.
I'm not a VB guy, but I think you could use Linq:
Dim mylines() As String = IO.File.ReadAllLines(mypath)
??? = mylines.Where(Function(s) s.StartWith("food")) //not sure of the return type
Check out: How do I append a 'where' clause using VB.NET and LINQ?