Andrew Andrew - 1 month ago 7
C# Question

Making first letter of a textbox upper case

I'm having trouble with this code. I want it to make the first letter of the Textbox upper case, but if the textbox is empty the program crashes. I know the problem is to do with the length of the substring, so if anyone can help me fix this it would be great!
NB: The name of the textbox is richTextBoxGuess and this code runs every time the text in the textbox changes.

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
}

TaW TaW
Answer

This will not destroy the previous formatting of the content:

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

Note that it doesn't not keep track of the changes and will not restore them when you keep adding at the front..

If you need culture invariance use the CultureInfo.CurrentCulture parameter of ToUpper()!

Comments