Skip to main content

Random Number/Line Selector in Visual Basic

Introduction: This tutorial is on how to create a 'Random Choice' tool which will randomly select either a line from a text file, or a random number. Design: For this we want; -Random Number- Numericupdown, numericupdown1, hold the minimum possible random number value. Numericupdown, numericupdown2, hold the maximum possible random number value. Button, button1, Select a random number. -Text File Line Selector- Button, button2, Select the file and choose a random number, converted to line. Imports: The first thing we need to do is import the System.IO namespace to allow us to interact with files...
  1. Imports System.IO
Random Number: For the random number tool, on the button1 click event, we are going to first create the Random variable globally which will be used in both the random number and file line selector tools...
  1. Dim random As New Random
Next we are simply going to messagebox (msgbox) a random number between the numericupdown1 and numericupdown2 (min and max values) converted to a string...
  1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  2. Dim number As Integer = random.Next(NumericUpDown2.Value)
  3. Dim isGood As Boolean = False
  4. While (Not isGood)
  5. If (number >= NumericUpDown1.Value) Then
  6. isGood = True
  7. Else : number = random.Next(NumericUpDown2.Value)
  8. End If
  9. End While
  10. MsgBox(number.ToString())
  11. End Sub
We loop around until the number is a value higher than the numericupdown1.value (minimum from the form design) because we only set the maximum upon calling the random.Next function from the numericupdown2. Random Line: For the random line selector, we first create, set properties for, and display a new OpenFileDialog to allow the user to select a .txt Text file for the input of the tool. We then create a new list of string named 'lines' and read the entire text file to the list. Finally we get a random number using our globally available 'random' variable and output the line at the index of that random number...
  1. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  2. Using fo As New OpenFileDialog
  3. fo.Filter = "Text Files | *.txt"
  4. fo.RestoreDirectory = True
  5. fo.Multiselect = False
  6. fo.ShowDialog()
  7. If (Not fo.FileName = Nothing) Then
  8. Dim lines As New List(Of String)
  9. Using sr As New StreamReader(fo.FileName)
  10. While sr.Peek <> -1
  11. lines.Add(sr.ReadLine())
  12. End While
  13. End Using
  14. Dim number As Integer = random.Next(lines.Count)
  15. MsgBox(lines(number))
  16. End If
  17. End Using
  18. End Sub

Add new comment