Home > OS >  How to declare a variable depending on user input in visual basic
How to declare a variable depending on user input in visual basic

Time:10-29

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.

CodePudding user response:

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

CodePudding user response:

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