2016-07-04 67 views
0

我試圖製作一個程序,只要在文本框中輸入字母,字母中的字母數就會出現在標籤中。 .... 我已經嘗試了一些代碼是這樣的:如何在文本框中輸入時在標籤中顯示字母數字

private void textBox1_TextChanged(object sender, EventArgs e) 
     { 
      string userInput = textBox1.Text; 
      char charCount; 
      charCount = userInput[0]; 

      label1 = charCount.Length.ToString(); 
     } 

但我無法找到我的解決我的問題.....

我欣賞的幫助下,我能得到....

+0

'label1.Text = textBox1.Text.Lengrh.ToString();'顯示輸入長度不是「字母長度」和假設'label1'是一個標籤的Winforms – Plutonix

+0

它總是26,不管哪個信你類型。 –

+0

你想要最後一個字母的數量,如A == 1,B == 2 ... Z == 26嗎? – Logman

回答

0

顯示字母表中的字母位置。

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    string userInput = textBox1.Text;   //get string from textbox 
    if(string.IsNullOrEmpty(userInput)) return; //return if string is empty 
    char c = char.ToUpper(userInput[userInput.Length - 1]); //get last char of string and normalize it to big letter 
    int alPos = c-'A'+1;       //subtract from char first alphabet letter 

    label1 = alPos.ToString();     //print/show letter position in alphabet 
} 
+0

嘿Logman,感謝您的幫助!它對我的項目非常有幫助! –

+0

@JanChristopherSantos樂於助人。如果您對我的答案滿意,請將其標記爲已接受。 – Logman

0

首先,你需要找到一個事件,這是觸發,當你的文字在文本框中被改變。例如KeyUp。然後你需要使用這樣的代碼註冊一個函數。

your_textbox.KeyUp += your_textbox_KeyUp; 

Visual Studio將通過創建一個空函數來幫助您。

的功能應該是這樣的:

private void your_textbox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e) 
{ 
    your_label.Content = your_textbox.Text.Length.ToString(); 
} 

your_label.Content是將被顯示在標籤,在右側將得到您的文本框中的文本的長度項屬性。

如果你想在標籤不僅可以說數字,但在文本換它,使用的String.Format這樣的:

your_label.Content = String.Format("The text is {0} characters long", your_textbox.Text.Length); 

我的回答是,雖然瞄準了WPF。如果您使用WinForms,某些關鍵字可能會有所不同。

0

我相信你只想寫在文本框中字母(字母)的數量,這裏有一個簡單的代碼:

private void textbox_TextChanged(object sender, EventArgs e) 
{ 
    int i = 0; 
    foreach (char c in textbox.Text) 
    { 
     int ascii = (int)c; 
     if ((ascii >= 97 && <= 122) || (ascii >= 65 && ascii <= 90)) // a to z or A to Z 
      i++; 
    } 

    label1.Text = i.ToString(); 
} 

更簡單的代碼:

private void textbox_TextChanged(object sender, EventArgs e) 
{ 
    int i = 0; 
    foreach (char c in textbox.Text) 
     if (char.IsLetter(c)) 
      i++; 

    label1.Text = i.ToString(); 
} 
0

如果你正在尋找對於文本框中不同字母的數量,您可以使用:

textbox.Text.ToUpper().Where(char.IsLetter).Distinct().Count(); 
相關問題