随机字母选择文本框

时间:2014-11-04 04:05:51

标签: vb.net

所以这段代码是Neethu Soman,

Dim input As String = TextBox2.Text '<--- this should be input "Hello I am Greg" 
    TextBox2.Text = "" '<--- clear the textbox to store output
    Dim rnd As New Random '<---- generating new random number 
    For Each c As Char In input '<--- iterate through each character
        If rnd.Next() Mod 2 = 0 Then
            TextBox2.Text &= UCase(c) '<--- if true then print particular letter in upperCase
        Else
            TextBox2.Text &= LCase(c) '<--- if true then print particular letter in LowerCase
        End If
    Next

基本上做了应该做的事情,它将随机字母转换为低位,大写字母转换为50/50。虽然,一个问题是清除文本,并以新的转换形式重写它,这就是问题所在。有没有办法让这项工作无需清除文本?

1 个答案:

答案 0 :(得分:1)

感谢您尝试使用我的答案,您可以使用以下代码将随机字母转换为低级或大写50/50,而不使用TextBox2.Text = ""

Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
    Dim rnd As New Random'<--- Generating random number
    If rnd.Next() Mod 2 = 0 Then
        e.KeyChar = UCase(e.KeyChar) '<--- if true then change key char to upperCase
    Else
        e.KeyChar &= LCase(e.KeyChar) '<--- if true then change key char to LowerCase
    End If
End Sub

如果您想在按钮点击中执行此操作:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim randomString As String = ""
    Dim rnd As New Random
    For Each c As Char In TextBox2.Text
        If rnd.Next() Mod 2 = 0 Then
            randomString &= UCase(c)
        Else
            randomString &= LCase(c)
        End If
    Next
    TextBox2.Text = randomString
End Sub