使用计时器生成特定的随机生成代码

时间:2015-06-04 16:24:18

标签: vb.net

我想在计时器结束时随机生成代码。

但我想使用此代码ABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789

格式为XXXX-XXXX-XXXX(用随机生成的数字/字母替换X)

我想在此

中插入代码
 Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    ProgressBar1.Increment(3)
    If ProgressBar1.Value = 100 Then
        TextBox1.Text = "replace textbox by code"
        Timer1.Stop()
    End If
End Sub

2 个答案:

答案 0 :(得分:0)

这是使用LINQ的解决方案。

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    ProgressBar1.Increment(3)
    If ProgressBar1.Value = 100 Then
        Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        Dim random = New Random()
        Dim num1 = New String(Enumerable.Repeat(chars, 4).Select(Function(s) s(random.Next(s.Length))).ToArray())
        Dim num2 = New String(Enumerable.Repeat(chars, 4).Select(Function(s) s(random.Next(s.Length))).ToArray())
        Dim num3 = New String(Enumerable.Repeat(chars, 4).Select(Function(s) s(random.Next(s.Length))).ToArray())
        Dim result = num1 & "-" & num2 & "-" & num3
        TextBox1.Text = result
        Timer1.Stop()
    End If
End Sub

答案 1 :(得分:0)

有了这个,您只需将TextBox1.Text =更改为指向getNewRandomString()功能。

Private Function getNewRandomString() As String
    Dim sb As New StringBuilder
    For i = 1 To 3
        For j = 1 To 4
            sb.Append(getNewRandomLetter())
        Next
        sb.Append("-")
    Next
    Return sb.ToString.Trim("-")
End Function

Private Function getNewRandomLetter() As Char
    Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    Return (chars(GetRandom(0, chars.Length - 1)))
End Function

Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
    Static Generator As System.Random = New System.Random()
    Return Generator.Next(Min, Max + 1)
End Function