Want this random number generator to generate 10 answers and add to a list box - vb.net

I am trying to keep some skills by writing a application during my semester break at school and have found some issues I don't know the answer to.
I am trying to get this code to generate 10 results and concatenate them to a ListBox named lstPhoneNumbers. Here is what I've tried:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Calculate Random Prefix based upon selected city
If lstBoxCity.SelectedItem.ToString = "Bethany" Then
' Initialize the random-number generator.
Randomize()
Dim Bethany As String() = {"298", "342", "443", "644", "712", "755", "759", "777", "779", "847"}
' Generate random value between 1 and then length of your Bethany array
Dim randomBethany As String = Bethany(CInt((Bethany.Count * Rnd()) + 1))
MsgBox(randomBethany.ToString)
End If
* Edited for Steven Doggart**
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Calculate Random Prefix based upon selected city
If lstBoxCity.SelectedItem.ToString = "Bethany" Then
Dim Bethany As String() = {"298", "342", "443", "644", "712", "755", "759", "777", "779", "847"}
For i As Integer = 0 To 9
lstPhoneNumbers.Items.Add(Bethany(RandomPrefix.Next(0, Bethany.Count - 1)))
Next
End If
End Sub

You really should be using the Random class rather than the old-VB6-style Rnd method. Even if you are using Rnd, you should, ideally, only be calling Randomize once, when the program starts, not every time the button is clicked. To do this with the Random class, first you should create a Random object as a private field on your form, like this:
Public Class MyForm
Private rand As New Random()
' ...
Then, in your button click event handler, you need to create a For loop which generates 10 random numbers, adding each one to the ListBox control as it does so:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'...
For i As Integer = 0 to 9
lstPhoneNumbers.Items.Add(Bethany(rand.Next(0, Bethany.Count - 1)))
Next
End Sub

Related

How to remove an item in a two dimensional array with a list box

Hi I have an assignment for coding and I am having a hard time to figure out how to code it. My teacher wanted us to build a program that uses a list box that holds product names and a 2-D array that holds quantity in stock and price. Then in the one of the buttons in the application, which is the remove button, the item in the list box as well as the data from the array should be removed. When the user deletes an item, not only must the list loose the name of the item but the 2-D array must also be readjusted.
I am sorry. My brain just doesn't want to do what your teacher wants. If you can make sense of the following, maybe you can convince your teacher not to ask you to use 2D arrays in this instance.
Public Class Product
'These are automatic properties
'The compiler provides the getter, setter and backer fields.
Public Property Name As String
Public Property Quantiy As Integer
Public Property Price As Double
'ToString is a method inherited from Object. It will return a fully
'qualified name of the Type, not what we want in a ListBox
'The ListBox will call .ToString on Product and we will get the Name
'property of the Product object.
Public Overrides Function ToString() As String
Return Name
End Function
Public Sub New(prodName As String, prodQuantity As Integer, prodPrice As Double)
'We add a parameterized Constructor to make it easy to add our Product objects
'to the ListBox. Intelisense will help out once we type the New keyword
Name = prodName
Quantiy = prodQuantity
Price = prodPrice
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'The New keyword calls the Constructor of the Product class
'so a Product object is added to the ListBox
ListBox1.Items.Add(New Product("Bell", 30, 2.98))
ListBox1.Items.Add(New Product("Book", 7, 200))
ListBox1.Items.Add(New Product("Candle", 42, 14.99))
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
'When a Product is deleted from the ListBoX with the RemoveItem button
'this event will fire. (The index changed) -1 means nothing is selected which is
'what happens after the delete. If Nothing is selected our cast will fail and
'we will get an exception.
If ListBox1.SelectedIndex <> -1 Then
'The ListBox items are objects but underneath the objects are Products
'so we can Cast the object back to a Product
Dim p As Product = CType(ListBox1.SelectedItem, Product)
'All the properties of the Procuct are then available
MessageBox.Show($"Product Name is {p.Name}. There are {p.Quantiy} on hand. The price is {p.Price:N2}")
End If
End Sub
Private Sub btnRemoveItem_Click(sender As Object, e As EventArgs) Handles btnRemoveItem.Click
ListBox1.Items.Remove(ListBox1.SelectedItem)
End Sub
End Class
This should work, though it's really the wrong way to approach this:
LBProducts = Form ListBox
lblQuantity = Form Label
lblPrice = Form Label
btnDelete = Form Button
Public Class Form1
'5 Rows, (Price, Qty)
Private ProductArray(5, 1) As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
LBProducts.Items.Add("Apples")
LBProducts.Items.Add("Bananas")
LBProducts.Items.Add("Grapes")
LBProducts.Items.Add("Oranges")
LBProducts.Items.Add("Peaches")
For x = 0 To 5
ProductArray(x, 0) = x
ProductArray(x, 1) = 1
Next
End Sub
Private Sub LBProducts_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBProducts.SelectedIndexChanged
Dim Index = LBProducts.SelectedIndex()
If Index >= 0 Then
lblPrice.Text = "Price: " & ProductArray(Index, 0)
lblQuantity.Text = "Qty: " & ProductArray(Index, 1)
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim Index = LBProducts.SelectedIndex()
If Index >= 0 Then
LBProducts.Items.RemoveAt(Index)
Dim NewArray(UBound(ProductArray) - 1, 1) As Integer
Dim i As Integer = 0
For x = 0 To UBound(ProductArray)
If x <> Index Then
NewArray(i, 0) = ProductArray(x, 0)
NewArray(i, 1) = ProductArray(x, 1)
i += 1
End If
Next
ProductArray = NewArray
End If
End Sub
End Class

VB.NET Random unique generator

I'l trying to generate a unique random number generator with the snippet of code from below, but it's not working. The IF section is suppose to test if it's the first random number generated, if it is, it's suppose to add the first random number to the ArrayList, if it's not the first random number, it's supposed to check if the random number is already in the ArrayList and if it's in the ArrayList it's suppose to MsgBox and generate a new unique random number that is not already in the ArrayList and add it to the ArrayList, but it's not doing any of those. Any help would be greatly appreciated.
Public Class Form1
Dim r As New Random
Dim dLowestVal As Integer = 1
Dim dHighestVal As Integer = 26
Dim dItemAmount As Integer = 1
Dim RollCheck As New HashSet(Of Integer)
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnRollDice_Click(sender As Object, e As EventArgs) Handles btnRollDice.Click
lblRandomNo.Text = r.Next(dLowestVal, dHighestVal)
lblItemAmount.Text = dItemAmount
If dItemAmount = 1 Then
RollCheck.Add(Val(lblRandomNo.Text))
ElseIf (RollCheck.Contains(Val(lblRandomNo.Text))) Then
MsgBox("Already Exists")
lblRandomNo.Text = r.Next(dLowestVal, dHighestVal)
RollCheck.Add(Val(lblRandomNo.Text))
End If
dItemAmount = dItemAmount + 1
Thanks in advance.
You could replace your whole method with this simple one
' This is globally declared at the top of your form
Dim values As New List(Of Integer)
' This is called when you construct your form
' It will store consecutive integers from 1 to 25 (25 elements)
values = Enumerable.Range(1, 25).ToList()
This is the method that extract an integer from your values that is not already used
Private Sub Roll()
' Get an index in the values list
Dim v = r.Next(0, values.Count)
' insert the value at that index to your RollCheck HashSet
RollCheck.Add(values(v))
' Remove the found value from the values list, so the next call
' cannot retrieve it again.
values.Remove(values(v))
End Sub
And you can call it from the previous event handler in this way
Private Sub btnRollDice_Click(sender As Object, e As EventArgs) Handles btnRollDice.Click
if values.Count = 0 Then
MessageBox("No more roll available")
else
Roll()
End Sub
End Sub
The point of the HashSet is that since it doesn't allow duplicates you can just check the return value of Add() to determine whether the number was successfully inserted or if it already exists in the list.
If you want to keep trying until it succeeds all you have to do is wrap it in a loop:
If dHighestVal - dLowestVal >= RollCheck.Count Then
'If the above check passes all unique values are MOST LIKELY already in the list. Exit to avoid infinite loop.
MessageBox.Show("List is full!")
Return 'Do not continue.
End If
Dim Num As Integer = r.Next(dLowestVal, dHighestVal)
'Iterate until a unique number was generated.
While Not RollCheck.Add(Num)
MessageBox.Show("Already exists!")
Num = r.Next(dLowestVal, dHighestVal)
End While
lblRandomNo.Text = Num
An alternative way of writing the loop is: While RollCheck.Add(Num) = False.

Alternative Process

I have 2 buttons and a DataGridView with 2 Columns (0 & 1).
The 1st button transfers a randomized cell from the Column(1) to a TextBox. Then, it stores that Cell in variable (a), plus the cell that opposites it in variable (b).
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim rnd As New Random
Dim x As Integer = rnd.Next(0, Form1.DataGridView1.Rows.Count)
Dim y As Integer = 1
Dim a As String = Form1.DataGridView1.Rows(x).Cells(y).Value
Dim b As String = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
The 2nd button, however, is supposed to compare if another TextBox's text has the same string variable (b) has as Strings. Now, if so, then it has to display a certain message and so on...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox4.Text = b Then '<<< ISSUE HERE!
MsgBox("Correct! ^_^")
ElseIf TextBox4.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub
The problem is that the variable (b) is surely not shared across the two "private" subs. And so, there is NOTHING to compare to in the 2nd button's sub! I presume that the solution here is to split the "randomization process" into a separate function, then execute it directly when the 1st button gets activated. Furthermore, that function's variables have to be SHARED somehow, and I certainly don't know how!
Thanks for Mr. Olivier, the code has been improved significantly! Yet, I still encounter a "wrong" comparison issue, somehow!
Dim RND As New Random
Dim x As Integer
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
x = RND.Next(0, Form1.DataGridView1.Rows.Count)
tbxRoll.Text = GetCell(x, 1)
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If tbxSubmit.Text = GetCell(x, 0) Then
MsgBox("Correct! ^_^")
ElseIf tbxSubmit.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub</code>
Well, unbelievably, I read a guide about "comparison operations" in VB.net and tried out the first yet the most primal method to compare equality - which was to use .Equals() command - and worked like a charm! Thank God, everything works just fine now. ^_^
If tbxSubmit.Text.Equals(GetCell(x, 0)) Then
Alright now... This is going to sound weird! But, following Mr. Olivier's advise to investigate "debug" the code, I rapped the string I'm trying to compare with brackets and realized that it's been outputted after a break-line space! So, I used the following function to remove the "white-space" from both of the comparison strings! And it bloody worked! This time for sure, though. ^_^
Function RemoveWhitespace(fullString As String) As String
Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function
If RemoveWhitespace(tbxSubmit.Text) = RemoveWhitespace(GetCell(x, 0)) Then
Turn the local variables into class fields.
Dim rnd As New Random
Dim x As Integer
Dim y As Integer
Dim a As String
Dim b As String
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
x = rnd.Next(0, Form1.DataGridView1.Rows.Count)
y = 1
a = Form1.DataGridView1.Rows(x).Cells(y).Value
b = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
These fields can now be accessed from every Sub, Function and Property.
Of course Button3_Click must be called before Button2_Click because the fields are initialized in the first method. If this is not the case then you should consider another approach.
Create a function for the Cell access
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) _
As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
And then compare
If TextBox4.Text = GetCell(x, y - 1) Then
...
And don't store the values in a and b anymore. If y is always 1 then use the numbers directly.
If TextBox4.Text = GetCell(x, 0) Then
...
One more thing: give speaking names to your buttons in the properties grid before creating the Click event handlers (like e.g. btnRandomize). Then you will get speaking names for those routines as well (e.g. btnRandomize_Click).
See:
- VB.NET Class Examples
- Visual Basic .NET/Classes: Fields

Visual Basic - Create an application to pick a number

Hye,
I'm new with Visual Basic and i had a few problems.
I've create a new Windows Forms Application in Visual Basic. Using one TextBox and two Button. The TextBox for displaying the number. One button for Generate and another one for Help.
I want to create a simple application that will pick one of the listed number instead of generating it.
Example :
Each time I click on the Generate button, it will pick either 14412GG or TE921W or 13123SA only. The number will appear in the TextBox.
Evertime i click on Help button, a windows will pop-up with help messages. Multiple line messages.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
**This is for Generate button**
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
**This is for Help button**
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
**This is to display the number**
End Sub
End Class
Save those 3 values in an arrayList, create a Random class.
private static ArrayList values1 = new ArrayList{"14412GG","TE921W","13123SA"};
Random rnd = new Random();
int r = rnd.Next(values1.Count);
(string)values1[r]
Display the string when Generate button clicks.
TextBoxVariable.Text = (string)values1[r];
Use Messagebox.Show to display the help message.
MessageBox.Show(""Help message line1" + Environment.NewLine + "Help message line2";");
Hope this helps!
Here is what you need :
'Button 1
Dim pool As String = "ABCDEFGHIJKLMNOPQURSTUVWXYZ1234567890"
Dim cc As New Random
Dim count = 0
While count <= 6
textbox1.text = cc.Next(0, pool.Length)
'button2
msgbox("message line1" + vbnewline + "message line2.")
i hope it be useful to you .

parse rounds to whole

I am trying to parse a textbox.text with a input value of 15.75. Here is all the code.
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim lnVendorNo, lnInHouseID, lnInventoryPackID As Integer
Dim lcVendProdID, lcVendProdDesc, lcDeliverPack As String
Dim lnDelivPackCost, lnDelivPackCost2 As Short
Integer.TryParse(txtVendorNo.Text, lnVendorNo)
lcVendProdID = txtVendProdID.Text
Integer.TryParse(txtInHouseID.Text, lnInHouseID)
lcVendProdDesc = txtVendProdDesc.Text
lcDeliverPack = txtDeliverPack.Text
txtDeliverPackCost.Text = "15.75"
Decimal.TryParse(txtDeliverPackCost.Text, lnDelivPackCost)
' Value of lnDelivPackCost in watch window is 16 and type is short
lnDelivPackCost2 = Double.Parse(txtDeliverPackCost.Text)
' value of lnDelivPackCost2 in watch window is 16 and type is short
I have another sub with the following code that works just fine.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim value As String
Dim number As Decimal
Dim lnDelivPackCost As Decimal
' Parse a floating-point value with a thousands separator.
value = "1643.57"
If Decimal.TryParse(value, number) Then
Console.WriteLine(number) ' Value of number in watch = 1643.57
End If
txtDeliverPackCost.Text = "15.75"
Decimal.TryParse(txtDeliverPackCost.Text, lnDelivPackCost) ' Value on lnDelivPackCost in watch = 15.75D
End Sub
Can anyone tell me why the parses work on one sub and not the other sub. Is it because of parsing to integers earlier in the sub. I am going bonkers trying to figure this out. Any help would be appreciated.
Larry