如何在文本框中输入时在标签中显示字母数字

问题描述:

我试图制作一个程序,只要在文本框中输入字母,字母中的字母数就会出现在标签中。 .... 我已经尝试了一些代码是这样的:如何在文本框中输入时在标签中显示字母数字

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

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

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

首先,你需要找到一个事件,这是触发,当你的文字在文本框中被改变。例如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,某些关键字可能会有所不同。

我相信你只想写在文本框中字母(字母)的数量,这里有一个简单的代码:

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(); 
} 

如果你正在寻找对于文本框中不同字母的数量,您可以使用:

textbox.Text.ToUpper().Where(char.IsLetter).Distinct().Count();