我在使用此代码时遇到问题。我希望它使Textbox大写的第一个字母,但如果文本框为空,程序崩溃。我知道问题与子串的长度有关,所以如果有人能帮我解决这个问题,那就太好了! 注意:文本框的名称是richTextBoxGuess,每次文本框中的文本发生更改时,此代码都会运行。
if (char.IsLower(Convert.ToChar(richTextBoxGuess.Text.Substring(0, 1))) ) // Checks if first letter is lower case
{
richTextBoxGuess.Text = richTextBoxGuess.Text.Replace(richTextBoxGuess.Text.Substring(0, 1), richTextBoxGuess.Text.ToUpper()); // Changes first letter to uppercase
richTextBoxGuess.SelectionStart = 2; // Puts cursor after first letter
}
答案 0 :(得分:2)
检查richTextBoxGuess是空还是空
if( richTextBoxGuess != ""){ // or different from null
if (char.IsLower(Convert.ToChar(richTextBoxGuess.Text.Substring(0, 1))) ){
//your code
}
}
答案 1 :(得分:2)
这不会破坏以前格式的内容:
private void richTextBoxGuess _TextChanged(object sender, EventArgs e)
{
if (richTextBoxGuess .Text.Length <= 0) return;
string s = richTextBoxGuess.Text.Substring(0, 1);
if (s != s.ToUpper())
{
int curSelStart = richTextBoxGuess.SelectionStart;
int curSelLength = richTextBoxGuess.SelectionLength;
richTextBoxGuess.SelectionStart = 0;
richTextBoxGuess.SelectionLength = 1;
richTextBoxGuess.SelectedText = s.ToUpper();
richTextBoxGuess.SelectionStart = curSelStart;
richTextBoxGuess.SelectionLength = curSelLength;
}
}
请注意,它不会跟踪更改,并且在您继续添加前端时无法恢复它们。
如果您需要文化不变性,请使用CultureInfo.CurrentCulture
的{{1}}参数!
答案 2 :(得分:1)
编写此扩展方法:
public static string CapitalizeFirstLetter(this string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
return input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) + input.Substring(1);
}
然后将其用作
richTextBoxGuess.Text = richTextBoxGuess.Text.CapitalizeFirstLetter();
答案 3 :(得分:0)
private void _capitalizeFirstWord(Object sender, KeyPressEventArgs e)
{
if (_richTB.Text.Trim() == String.Empty)
{
e.KeyChar = char.ToUpper(e.KeyChar);
}
}
如果你想把每个单词都大写
char _pre,_cur;
_pre=' ';
private void _capitalizeEveryWord(Object sender, KeyPressEventArgs e)
{
_cur = e.KeyChar;
if (_richTB.Text.Trim() == String.Empty)
{
e.KeyChar = char.ToUpper(e.KeyChar);
}
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == ' ' && (!(_cur == _pre)) || e.KeyChar == '.' && (!(_pre == _cur)));
_pre=_cur
}