How to declare a variable depending on user input in visual basic - vb.net

I want to create a program where the user will input a number on a text box and the program will create a number of variables depending on the number when he/she pressed the submit button. (Windows Forms)
For example, user will input 3 on text box and when he/she pressed the submit button the program will create a variable labeled length1,length2,length3 as int inside the program to be use for other purposes later.

Try creating a list like this:
Private Numbers As New List(Of Number)
Private Class Number
Public Name As String
Public Value As Integer
End Class
Next create a procedure that will add integers and a name to the list:
Private Sub AddNumbers()
If IsNumeric(textbox1.Text) = false Then
Exit Sub
End If
For i = 1 to Convert.ToInt32(textbox1.Text)
Numbers.Add(New Number With {.Name = "length" & i, .Value = 0})
Next
End Sub
I assume that that the textbox is called textbox1. Then you can call the AddNumbers sub from the submit button like this:
AddNumbers()
You can retrieve a number from the list like this:
Numbers(0).Value

Using List to create a number of Integer variables.
Public length As List(Of Integer)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i = 1 To Convert.ToInt32(TextBox1.Text)
length.Add(0)
Next
End Sub
Then you can get the variable by length(0).
Don't forget to limit the TextBox to only enter numbers and backspace.
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If Char.IsDigit(e.KeyChar) Or e.KeyChar = Chr(8) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub

Related

Converting check List in VB.NET to integer

This is my first time working with VB.Net It's a college assignment and is already due for submission.I want to create a simple program that determines if a user has Ebola or not. So, there is a list of checkbox containing the core symptoms of Ebola. If the user selects 4 or more there should be a prompt message saying the user most likely has Ebola otherwise user does not have Ebola.
I have created the form and it works but don't know how to implement the checkbox into numbers that will be summed up.
Here is the code for the form
Public Class Checkbxvb
Private Sub Checkbxvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = "Click to select the symptoms you are having"
CheckBox1.Text = "Fever"
CheckBox2.Text = "Loss of appetite"
CheckBox3.Text = "sore throat"
CheckBox4.Text = "Gastrointestinal Symptoms"
CheckBox5.Text = "Unexplained bleeding or bruising"
CheckBox6.Text = "Loss of weight"
Button1.Text = "Submit"
Button2.Text = "Close"
End Sub
I want to create a button that will collect the user input like I said earlier on. Thanks
If you are using a CheckListBox you can used its CheckedItems collection Count property to get what you need.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If CheckedListBox1.CheckedItems.Count > 3 Then
MessageBox.Show("You may have Ebola.")
Else
MessageBox.Show("You probably don't have Ebola.")
End If
End Sub
If you are using CheckBox controls add them to a List(Of T). The T stands for Type. Create a variable for the list at Form level so it can be seen from the Form.Load and the button click. Then you can loop through your collection and increment a counter when the Checked property is True.
Private CkBxList As New List(Of CheckBox)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CkBxList.AddRange({CheckBox1, CheckBox2, CheckBox3, CheckBox4})
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim counter As Integer
For Each cb In CkBxList
If cb.Checked Then
counter += 1
End If
Next
If counter > 3 Then
MessageBox.Show("You may have Ebola.")
Else
MessageBox.Show("You probably don't have Ebola.")
End If
End Sub
As you can see the code is much simpler with a CheckedListBox. Try to use the control that best suits your purpose.

How to transfer data from listbox to textbox in Visual Basic

I did some activity but I cant figure out how to retrieve data from listbox1 to textbox1. Example in the listbox1 there are 4 names: John, Jorge, Joe. Then I want to transfer Joe from listbox1 to textbox1. I did an arraylist where I adding those 3 names in the listbox1 but I didn't know how to retrieve the name "Jorge" from listbox1 to textbox1. Send help.
Here's the code where I try to retrieve one of the name from listbox1 to textbox1
Private Sub Retrievebtn_Click(sender As Object, e As EventArgs) Handles Retrievebtn.Click
If textbox1.Text = ListBox1.Items.Count Then
textbox1.Text = ArrayofNames(x)
End If
End Sub
Here's the whole code
Public Class Form1
Dim ArrayofNames() As String
Dim x As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Retrievebtn_Click(sender As Object, e As EventArgs) Handles Retrievebtn.Click
If textbox1.Text = ListBox1.Items.Count Then
textbox1.Text = ArrayofNames(x)
End If
End Sub
Private Sub Addbtn_Click(sender As Object, e As EventArgs) Handles Addbtn.Click
Dim x As Integer = 0
ReDim ArrayofNames(x)
For x = 0 To ArrayofNames.Length - 1
ArrayofNames(x) = Addtextbox.Text
ListBox1.Items.Add(ArrayofNames(x))
Next
End Sub
Private Sub removeBtn_Click(sender As Object, e As EventArgs) Handles removeBtn.Click
ListBox1.Items.Remove(ListBox1.SelectedItem)
End Sub
End Class
Here's the Image of the interface i try to retrieve the name Joe but it wasn'tshowing
Let's go over the code you posted.
In the retrieve button click event you are comparing and Integer to a String with textbox1.Text = ListBox1.Items.Count This won't compile with Option Strict On. You do have Option Strict On, don't you? You should always have this on.
On the next line, you assign the value of ArrayofNames(x), where x refers to your form level variable, to a text box's Text property. Since the value of x is never changed anywhere in the code this will always return the 0 index in the array. (The first element) I can't imagine why it should matter that the Textbox.Text should equal the count of the ListBox items.
In the add button click event you first declare a local variable x. Any code in the method will use this x, not the form level x. You ReDim (without the Preserve keyword) the array to an array with a single element. Your For loop is silly because the length of ArrayofNames is 1, so it is 0 To 0.
The ArrayofNames will never have more than a single element and it will be overwritten each time the add button is clicked.
Fortunately the Listbox maintains its own collection of items.
We can use this collection to simplify your code. Just add the contents of the text box to the the list items.
To retrieve a value from the list box you must first determine if the user has entered a valid index. First, is the entry a valid Integer and is it an index present in the list box.
Remember that .net collections start at index 0.
I use default names in my test program but you should continue to use meaningful names for your controls.
'Your add button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim index As Integer
If Integer.TryParse(TextBox1.Text, index) AndAlso index >= 0 AndAlso ListBox1.Items.Count - 1 >= index Then
TextBox2.Text = ListBox1.Items(index).ToString
End If
End Sub
'Your add button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ListBox1.Items.Add(TextBox3.Text)
End Sub

Having trouble with a lottery software

sorry to come in here like this looking for answers, but im actually really stumped. Im supposed to make an application using 2 forms, one to generate its own array and store user entered numbers into another array, and then display them on the second form and tell you how many of the numbers are in common
I cant get the numbers to show up on the second form at all, and I also cant really understand how to get how many numbers are matching, but I will when I can reference them properly in form 2. I got the arrays set up perfectly, but I cant even call the numbers from them to form 2. I need help calling the arrays from the first form to display on the next
Form 1 code
Public Class Form1
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Shared random As New Random()
Dim UserArray(4) As String
Dim LotteryArray(4) As String
Public Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
If txtNumbers.Text <> "" Then
For i As Integer = 0 To 4
If UserArray(i) = "" Then
UserArray(i) = txtNumbers.Text
End If
Next
End If
For n As Integer = 0 To 9
Dim RandomNumber As Integer = CInt(Int(Rnd() * 5) + 1)
LotteryArray(4) = CStr(RandomNumber)
Next
End Sub
End Class
Form 2 Code
Public Class Form2
Public Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
lblUser1.Text = Form1.UserArray(0)
lblUser2.Text = Form1.UserArray(1)
lblUser3.Text = Form1.UserArray(2)
lblUser4.Text = Form1.UserArray(3)
lblUser5.Text = Form1.UserArray(4)
lblRand1.Text = Form1.LotteryArray(0)
lblRand2.Text = Form1.LotteryArray(1)
lblRand3.Text = Form1.LotteryArray(2)
lblRand4.Text = Form1.LotteryArray(3)
lblRand5.Text = Form1.LotteryArray(4)
If Form1.LotteryArray(4) = Form1.UserArray(4) Then
MessageBox("CONGRATULATIONS!", "You Are The GRAND PRIZE WINNER!")
End If
Me.Close()
End Sub
End Class
I will address your first question. How to get your numbers into your second form.
You main problem is the Access modifier you used for your arrays. Dim is the equivalent of Private which means that the variable is only visible within the class. Friend is visible anywhere in the assembly. See https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/declared-elements/access-levels for more information. Don't change your event procedure Access to Public.
You have to let the user fill in another guess. The first loop in the Check button will only enter the same input 5 times. You need one entry on every click but you need to keep track of where you are in the array. Private NumberOfGuesses As Integer Note that this variable is Private. It doesn't need to be seen outside of the Form1 class.
We don't need to refill the LotteryArray on every click so I did it once in the Form.Load You were trying to use the Random class the way you use the old vb6 Random. The .net class is much easier.
To display the arrays on Form2, I used list boxes and loops. Saved a bit of typing.
If you still have a question about part 2 of your problem post another question. Show what you have tried.
Public Class Form1
Private random As New Random()
Friend UserArray(4) As Integer
Friend LotteryArray(9) As Integer
Private NumberOfGuesses As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For n As Integer = 0 To 9
Dim RandomNumber As Integer = random.Next(0, 10)
LotteryArray(n) = RandomNumber
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If NumberOfGuesses > 4 Then
MessageBox.Show("You have used up your guesses")
Form2.Show()
Me.Close()
End If
If TextBox1.Text <> "" Then
UserArray(NumberOfGuesses) = CInt(TextBox1.Text)
NumberOfGuesses += 1
TextBox1.Clear()
TextBox1.Focus()
End If
End Sub
End Class
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each number In Form1.UserArray
ListBox1.Items.Add(number)
Next
For Each number In Form1.LotteryArray
ListBox2.Items.Add(number)
Next
End Sub
End Class

Try to read text , put on list , then compare on list and finally replace txt file

Trying to read a .txt file , put items to list, then on textbox change compare if the string exists in the list. Finally write the new list on the same .txt file.
Public Class Form1
Dim stockList As New List(Of String)
private sub
ListBox1.Items.AddRange(IO.File.ReadAllLines("C:\Users\path\file.txt"))
end sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles
TextBox1.ReadOnlyChanged
Dim text As String = TextBox1.Text
If TextBox1.Text <> "TRAINING" Then
For Each item As Object In ListBox1.Items
If item.ToString = text Then
MsgBox("This code has already been used.", 0, "cheat attempt violation") ' Else alert the user that item already exist
Else
ListBox1.Items.Add(TextBox1.Text)
End If
Next
End If
IO.File.WriteAllLines("C:\Users\path\file.txt", ListBox1.Items.Cast(Of String).ToArray)
End Sub
Instead of using a UI control to store data, you should store the data in a variable. I'm not sure if you really need to show the data in a ListBox, so in the following example code I didn't.
If you use a List(Of String) instead of an array of strings, it is simpler to add another item before saving it.
The Contains method I used in the example can take a second parameter which does the comparison of the item - I guessed that you might want to ignore the case (e.g. "ABC" is the same as "aBc") so I used StringComparer.CurrentCultureIgnoreCase.
I suspect that you want to use the Control.Validating Event instead of the TextChanged event. When the data has been validated, the Control.Validated event handler is used to save it.
I put one TextBox and one Button on the form, so that the focus could change away from the TextBox, e.g. when pressing tab, to fire the validating event.
Imports System.IO
Public Class Form1
Dim dataFile As String = "C:\temp\grains.txt"
Dim alreadyUsed As List(Of String) = Nothing
Sub LoadAlreadyUsed(filename As String)
'TODO: Add exception checking, e.g., the file might not exist.
alreadyUsed = File.ReadAllLines(filename).ToList()
End Sub
Sub SaveAlreadyUsed(filename As String)
File.WriteAllLines(dataFile, alreadyUsed)
End Sub
Function CodeIsAlreadyUsed(newCode As String) As Boolean
Return alreadyUsed.Contains(newCode, StringComparer.CurrentCultureIgnoreCase)
End Function
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
' Do nothing if the user has clicked the form close button
' See https://stackoverflow.com/questions/15920770/closing-the-c-sharp-windows-form-by-avoiding-textbox-validation
If Me.ActiveControl.Equals(sender) Then
Exit Sub
End If
Dim txt = DirectCast(sender, TextBox).Text
If CodeIsAlreadyUsed(txt) Then
MessageBox.Show("This code has already been used.", "Cheat attempt violation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
e.Cancel = True
End If
End Sub
Private Sub TextBox1_Validated(sender As Object, e As EventArgs) Handles TextBox1.Validated
' The Validated event is raised before the FormClosing event.
' We do not want to save the data when the form is closing.
If Me.ActiveControl.Equals(sender) Then
Exit Sub
End If
Dim txt = DirectCast(sender, TextBox).Text
alreadyUsed.Add(txt)
SaveAlreadyUsed(dataFile)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadAlreadyUsed(dataFile)
End Sub
End Class

How do I create a boolean function that will determine if a group of radio buttons have all been selected and return a message box to the user?

I was given an assignment to create a program for an airline in which allows the user to select their seat. After each seat is selected, I am suppose to set the corresponding buttons array element’s Enabled property to False. Once all of the available seats are taken, I am required to create a Boolean function to check if there are any seats available. If all seats are taken, then a message box should pop up and tell the user this information.
The problem is I can't seem to get the message box to show up once all of the seats are taken. Please help me figure this out. I have attached my code below. Thanks!
Public Class Form1
Private availableSeats(7) As Boolean
Private buttons(7) As RadioButton
Private truth As Boolean
Private Sub UpdateSeatButtons()
For x As Integer = 0 To 7
If availableSeats(x) = False Then
buttons(x).Enabled = False
End If
Next
End Sub
Private Function CheckForAvailable() As Boolean
Dim seat As Boolean
For Each seat In availableSeats
If seat = True Then
truth = True
Return truth
End If
Next
truth = False
Return truth
End Function
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 0 To 7
buttons(i) = New RadioButton
Next
buttons(0) = seat10ARadioButton
buttons(1) = seat11ARadioButton
buttons(2) = seat12ARadioButton
buttons(3) = seat13ARadioButton
buttons(4) = seat10BRadioButton
buttons(5) = seat11BRadioButton
buttons(6) = seat12BRadioButton
buttons(7) = seat13BRadioButton
For i As Integer = 0 To 7
buttons(i).Checked = False
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Caption As String = "Seat Update"
Dim boxButtons As MessageBoxButtons = MessageBoxButtons.OK
Dim Result As DialogResult
For z As Integer = 0 To 7
Dim Message As Integer = z
If buttons(z).Checked Then
availableSeats(z) = False
Result = MessageBox.Show(Message, Caption, boxButtons)
Else
availableSeats(z) = True
End If
Next
UpdateSeatButtons()
CheckForAvailable()
If truth = False Then
MessageBox.Show("This flight is full", "No seats available", MessageBoxButtons.OK)
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Application.Exit()
End Sub
End Class
Below is a set of instructions my professor gave me:
Instructions
In this case, you will create a Visual Basic solution that allows the
Island Breezes Sea Planes airline to assign seats to passengers. This
program demonstrates the use of parallel one-dimensional arrays. One
array is used to represent the availability of each seat. The other
array is used to manage the RadioButton controls on the form. It
introduces the technique of using an array of RadioButton objects.
Here are instructions on how to design and code this project:
Step 1: Create the Project: Create a Visual Basic Project using the
project name “AirplaneSeating”.
Step 2 – Design the Form: Design the form as shown in Figure 1. You
will need two button controls, one textbox, one group box, eight radio
buttons, one picture box, and two label controls.
Step 3 – Declare the form-level arrays: Declare an array of Boolean
values to indicate the availability of each seat:
Private availableSeats(7) As Boolean Declare an object array as type RadioButton:
Private buttons(7) As RadioButton
Step 3 – Add code in the Form’s Load event to initialize the arrays:
Each object in the buttons array must be initialized to be a
RadioButton object. In the Form’s Load event, write a loop to
initialize each array element using this syntax: buttons(i) = New
RadioButton
After this loop, load each individual radio button into an array
position, using this syntax (in this example, the first radio button
control’s name is seat10ARadioButton, and it is being loaded into the
first object array position):
buttons(0) = seat10ARadioButton Do this for each radio button control.
Finally, write a loop to set the Checked property of all of the
buttons array elements to False.
Step 4 – Create a sub procedure for showing seat availability on the
form: Create a sub procedure named UpdateSeatButtons that will loop
through the availableSeats array. If an element in the availableSeats
array equals False, set the corresponding buttons array element’s
Enabled property to False to visually indicate that this seat is no
longer available.
Step 5 – Create a function for determining if there are any seats
still available: Create a Boolean function named CheckForAvailable
that will loop through the c array to determine if there are any seats
still available. If there is at least one seat available, return a
True value; otherwise, return False.
Step 6 – Add code in the Confirm Seat button’s Click event to update
the seating chart: Loop through the buttons array to determine which
button was selected. Set the corresponding availableSeats array
element to False. Then call the UpdateSeatButtons sub procedure to
update the visual seating chart.
Call the CheckForAvailable function to determine whether you should
display a message indicating that the flight is full.
Step 7 – Finish up:
Be sure to add the code for the Exit button.
Step 8: Save and run Save all files, then start the application.
Test the program using various selections. Figure 2 shows a sample
run of this program, with the user’s choices shown. Notice that the
unavailable seats are grayed.
Thank you so much for all of your help! I was able to solve the problem. I have attached my final code below. Thanks again!
Public Class Form1
Private availableSeats(7) As Boolean
Private buttons(7) As RadioButton
Private truth As Boolean
Private Sub UpdateSeatButtons()
For z As Integer = 0 To 7
If availableSeats(z) = False Then
buttons(z).Enabled = False
End If
Next
End Sub
Private Function CheckForAvailable() As Boolean
Dim seat As Boolean
For Each seat In availableSeats
If seat = True Then
truth = True
Return truth
End If
Next
truth = False
Return truth
End Function
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For z As Integer = 0 To 7
buttons(z) = New RadioButton
Next
buttons(0) = seat10ARadioButton
buttons(1) = seat11ARadioButton
buttons(2) = seat12ARadioButton
buttons(3) = seat13ARadioButton
buttons(4) = seat10BRadioButton
buttons(5) = seat11BRadioButton
buttons(6) = seat12BRadioButton
buttons(7) = seat13BRadioButton
For z As Integer = 0 To 7
buttons(z).Checked = False
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Caption As String = "Seat Update"
Dim boxButtons As MessageBoxButtons = MessageBoxButtons.OK
Dim Result As DialogResult
For z As Integer = 0 To 7
Dim Message As Integer = z
If buttons(z).Checked Then
availableSeats(z) = False
Result = MessageBox.Show(Message, Caption, boxButtons)
ElseIf buttons(z).Enabled = False Then
availableSeats(z) = False
Else
availableSeats(z) = True
End If
Next
UpdateSeatButtons()
CheckForAvailable()
If truth = False Then
MessageBox.Show("This flight is full", "No seats available", MessageBoxButtons.OK)
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Application.Exit()
End Sub
End Class
In your for loop add buttons(z).Enabled = False:
For z As Integer = 0 To 7
Dim Message As Integer = z
If buttons(z).Checked Or buttons(z).Enabled = False Then
If buttons(z).Checked Then
Result = MessageBox.Show(Message, Caption, boxButtons)
End If
availableSeats(z) = False
Else
availableSeats(z) = True
End If
Next
Every time you press the button you set the availableSeats array to true except for the checked one including of course your disabled ones.
EDIT
Initialize availableSeats to true:
For i As Integer = 0 To 7
availableSeats(i) = True
Next
and
For z As Integer = 0 To 7
Dim Message As Integer = z
If buttons(z).Checked Then
Result = MessageBox.Show(Message, Caption, boxButtons)
availableSeats(z) = False
Exit For
End If
Next
valter
I would suggest a number of changes to your code. You do not need to create the buttons and availableSeats arrays; just use the controls themselves. This approach eliminates setting and testing for available seats. I created a new Sub that handles all RadioButton click events and disables the associated control. Let me know if I have misunderstood the requirements or need help interpreting my code.
Private Function CheckForAvailable() As Boolean
For Each ctl As Control In Controls
If TypeOf ctl Is RadioButton Then
If ctl.Enabled Then Return True ' could have tested for Checked too
End If
Next
Return False
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' no need to initialize anything here
End Sub
Private Sub SeatClicked(sender As Object, e As EventArgs) Handles RadioButton1.Click, RadioButton2.Click, RadioButton3.Click, RadioButton4.Click, RadioButton5.Click, RadioButton6.Click, RadioButton7.Click, RadioButton8.Click
If CType(sender, RadioButton).Checked Then
If CType(sender, RadioButton).Checked Then
CType(sender, RadioButton).Enabled = False
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim boxButtons As MessageBoxButtons = MessageBoxButtons.OK
If Not CheckForAvailable() Then
MessageBox.Show("This flight is full", "No seats available", MessageBoxButtons.OK)
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Application.Exit()
End Sub