如何在文本框中输入时在标签中显示字母表中的字母数
本文关键字:字母表 显示 文本 输入 标签 | 更新日期: 2023-09-27 17:54:30
我想做一个程序,每当你在文本框中键入一个字母,字母在字母表中的数字会出现在标签......我已经尝试了一些代码,像这样:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string userInput = textBox1.Text;
char charCount;
charCount = userInput[0];
label1 = charCount.Length.ToString();
}
但是我找不到解决问题的方法.....
如果能得到帮助我会很感激....
显示字母的位置
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
}
首先,您需要找到一个事件,当文本框中的文本被更改时触发该事件。例如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。内容是将显示在标签中的属性,右边的术语将获得文本框中文本的长度。
如果您希望标签不仅显示数字,而且将其包装在文本中,请使用String。格式如下:
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();