Visual Basic help

Associate
Joined
27 Jun 2006
Posts
1,473
Okay, thought it would be good to get back into playing with VB but hasn't it changed since I last had a go (VB4 - and I still have books!)

Anyway - I am looking for a bit of code that will randomly create a 5 character (A - Z) code and then assign it to a text box when someone clicks a button.

I can do it hardcoded (ie TextBox1.Text = "ABCDE") but not sure where to start with automating it!

Any pointers appreciated - my Google skills are failing me tonight :(

M.
 
Last edited:
You could use the RandomString function here, i.e.:

TextBox1.Text = RandomString(5, false)

Here's a VB version of that code (untested):
Code:
''' <summary>
''' Generates a random string with the given length
''' </summary>
''' <param name="size">Size of the string</param>
''' <param name="lowerCase">If true, generate lowercase string</param>
''' <returns>Random string</returns>
Private Function RandomString(size As Integer, lowerCase As Boolean) As String
	Dim builder As New StringBuilder()
	Dim random As New Random()
	Dim ch As Char
	Dim i As Integer = 0
	While i < size
		ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)))
		builder.Append(ch)
		System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
	End While
	If lowerCase Then
		Return builder.ToString().ToLower()
	End If
	Return builder.ToString()
End Function
 
Back
Top Bottom