我来到这里寻求帮助,告诉我如何使我的字符串生成器生成TextBox2中输入的字符串数量。例如,如果我在框中键入10,它将在RichTextBox1中生成10个字符串,如果我输入1则会生成1个等等。这是我的代码。
Public Function RandomString(ByVal length As Integer) As String
Dim strb As New System.Text.StringBuilder
Dim chars() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
Dim UpperBound As Integer = UBound(chars)
For x As Integer = 1 To length
strb.Append(chars(Int(Rnd() * UpperBound)))
Next
Return strb.ToString
End Function
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
Try
System.Diagnostics.Process.Start("Link Removed...")
Catch
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim rndstring As String
rndstring = RandomString(24)
RichTextBox1.Text = rndstring
End Sub
答案 0 :(得分:0)
您需要做的是修改Button1的点击处理程序,重复TextBox2
中指定的次数。但是,您应该验证用户是否也在文本框中指定了有效的数值。像这样:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim repeatCnt As Integer
'Check for valid numeric entry
If Integer.TryParse(TextBox2.Text, repeatCnt) Then
For repeatIdx As Integer = 1 To repeatCnt
Dim rndstring As String
'Generate random string...
rndstring = RandomString(24)
'...and append to text box with a line break
TextBox1.Text &= rndstring & vbCrLf
Next
Else
MessageBox.Show("Please enter a valid integer number in the text box")
End If
End Sub
额外的建议可能是将用户指定重复值的文本框更改为NumericUpDown控件。
另请注意,对于较大的重复值,由于字符串immutability,附加到文本框Text
属性不会有效,因此可能另一个StringBuilder
是合适的。
答案 1 :(得分:0)
您可以使用此方法(基本上它只是一个额外的For
- 循环):
Private Shared rnd As New Random()
Private Shared chars() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
Public Shared Function RandomStrings(ByVal length As Int32, count As Int32) As IEnumerable(Of String)
Dim builder = New System.Text.StringBuilder()
Dim strings = New List(Of String)
For c As Int32 = 1 To count
For l As Int32 = 1 To length
builder.Append(chars(rnd.Next(0, chars.Length)))
Next
strings.Add(builder.ToString())
builder.Clear()
Next
Return strings
End Function
创建100个长度为10的随机字符串:
Dim allStrings = RandomStrings(10, 100)