2014-11-04 19 views
0

因此,通過尼索曼這段代碼,隨機字母選擇適合文本框

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的機會。雖然,那個問題是清除文本,並以新的轉換後的格式重寫它,這是問題所在。有沒有辦法讓這項工作,而不必清除文本?爲使我的回答一試

+0

你將不得不要麼清除文字或者只是用新文本替換以前的文本,因爲字符串是不可改變在.NET – 2014-11-04 05:20:07

回答

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 
+0

我怎樣才能讓這個執行與按鈕? – Greg 2014-11-04 04:58:20

+0

查看答案的更新 – 2014-11-04 05:19:15

+0

謝謝!完美工作 – Greg 2014-11-04 05:20:14