Home > Back-end >  How to automatically lower case the 2nd letter of a word in a WPF textbox?(C#)
How to automatically lower case the 2nd letter of a word in a WPF textbox?(C#)

Time:07-20

I am trying to create a function which automatically lower cases the 2nd Letter of a Word in a textbox. I already tried it with this function but i ran into one problem:

After the function detects a 2nd letter of a word which isn't written in lower case it sets the letter to capital. But after that the writing cursor moves to the beginning of the textbox. (the cursor moves in front of the already written words)

private void Text1_KeyDown(object sender, KeyEventArgs e)
        {
            string erg;
            string input;
            input = Convert.ToString(Text1.Text);
            if (input.Length > 1)
            {
                erg = input[0]   input.Substring(1, 1).ToLower()   input[2..];
                Text1.Text = erg;
            }
        }

Thank You in advance!

CodePudding user response:

You need to remember and then set the CaretIndex to the correct position, like so

var originalIndex = Text1.CaretIndex;

// Your code

Text1.CaretIndex = originalIndex;

CodePudding user response:

well you can just do this

var secondChar = text[1].ToString();
var loweredString = text[0]   secondChar.ToLower()   text[2..];

and set loweredString to your textBox.

  •  Tags:  
  • c#
  • Related