Random Code Generator using VB.Net

0
121

Random Code Generator using VB.Net

Random Code Generator using VB.Net.

In this tutorial, you will learn how to create your own code generator based on your declared string value. This is good especially when you want to create a project that needs auto-generator code for special coupons or primary keys to an information.

Let’s create our new project and drag a label, text box and button. See the sample image below:

Random Code Generator using VB.Net

Next, let’s do coding! We will first create our function to return a random string. But first, you need to import System.Text to use the Class StringBuilder.

  1. Imports System.Text
  2.  
  3. Private Function autogenerateCode() As String
  4. Dim builder As New StringBuilder()
  5. Dim allowedCharacters As String = "abcd1234"
  6. Dim randomCode As New Random
  7.  
  8. For i As Integer = 1 To 4
  9. Dim index As Integer = randomCode.Next(0, allowedCharacters.Length)
  10. Dim randomCharacter As Char = allowedCharacters(index)
  11. builder.Append(randomCharacter)
  12. Next i
  13.  
  14. Dim randomString = builder.ToString()
  15. Return randomString
  16. End Function

Next, double click your button and add this line of code:

  1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  2. TextBox1.Text = autogenerateCode()
  3. End Sub

After that, try to run your system and push the button. You would notice that the system is giving a random code based on your allowedCharacters declared string in autogeneratecode() function and the length of your random code depends on your declared For loop to integer. Here’s the example output based on our code:

Random Code Generator using VB.Net

Let’s try to change the allowedCharacters string and the for loop to integer.

  1. Dim allowedCharacters As String = "wxyz0987"
  2.  
  3. For i As Integer = 1 To 6
  4. Dim index As Integer = randomCode.Next(0, allowedCharacters.Length)
  5. Dim randomCharacter As Char = allowedCharacters(index)
  6. builder.Append(randomCharacter)
  7. Next i

Try to run your new code and see your results. Here’s my output:

Random Code Generator using VB.Net

Congratulations! You now learned how to create your own auto-generator code using VB.Net!

For questions or any other concerns or thesis/capstone creation with documentation, you can contact me through the following:

E-Mail: [email protected]

Facebook: facebook.com/kirk.lavapiez

Contact No.: +639771069640

Ian Hero L. Lavapiez

BSIT Graduate

System Analyst and Developer

Related topic(s) that you may like:

 

 

 

 

 

 

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here