在textBox1_TextChanged事件中将空格后的第一个字母改为大写
本文关键字:第一个 TextChanged textBox1 事件 空格 | 更新日期: 2023-09-27 18:02:13
我有一个关于TextBox的查询。当我在文本框中输入时,单词会自动改变。例如:"我的名字是kumar"到"我的名字是kumar",应该在textBox1_TextChanged事件上完成。
目前我在休假事件
private void textBox1_Leave(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Substring(0, 1).ToUpper() + textBox1.Text.Substring(1);
}
请帮助我完成它。提前非常感谢。:)
使用TextInfo。ToTitleCase方法
private void textBox1_Leave(object sender, EventArgs e)
{
TextInfo myTI = new CultureInfo("en-US",false).TextInfo;
textBox1.Text = myTI.ToTitleCase(textBox1.Text)
}
作为上一个答案的后续,如果您将以下几行添加到正文的其余部分,您将确保保持正确的行为:
textBox1.SelectionStart = textBox1.TextLength;
textBox1.SelectionLength = 0;
所以完整的解决方案是:
private void textBox1_Leave(object sender, EventArgs e)
{
//Original from JW's answer
TextInfo myTI = new CultureInfo("en-US",false).TextInfo;
textBox1.Text = myTI.ToTitleCase(textBox1.Text);
//New lines to ensure the cursor is always at the end of the typed string.
textBox1.SelectionStart = textBox1.TextLength;
textBox1.SelectionLength = 0;
}
这应该能解决你的问题:
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
textBox1.Text = myTI.ToTitleCase(textBox1.Text);
textBox1.SelectionStart = textBox1.Text.Length;
}
我会在这里使用Regex
,因为它更容易实现,我不认为你的TextBox
将持有大字符串。由于您希望在编写时自动更正字符串,因此需要使用TextChanged
事件而不是Leave
事件:
private void textBox1_TextChanged(object sender, EventArgs e)
{
Regex regex = new Regex(" [a-z]");
foreach (Match match in regex.Matches(textBox1.Text))
textBox1.Text = regex.Replace(textBox1.Text, match.Value.ToUpper());
}