Convert all characters of a string to uppercase, except for some specific characters

1.9k views Asked by At

I am trying to prevent some characters from being uppercase, while all others has to be.

For an example if I write something in the textbox, it automatically writes all characters uppercase, but everytime I enter the letter "k" it has to be lowercase.

Does any one know a way of achieving this?

private void textBox3_TextChanged(object sender, EventArgs e)
{
    // Navn/Name Text Box 


}
4

There are 4 answers

0
René Vogt On BEST ANSWER

In your textBox3_TextChanged event handler you can simply "correct" the text and set it back.
You'll have to remember the cursor position (and selection) so that the user does not get interrupted while typing:

private void textBox3_TextChanged(object sender, EventArgs e)
{
    int start = textBox3.SelectionStart;
    int length = textBox3.SelectionLength;
    textBox3.Text = textBox3.Text.ToUpper().Replace("K", "k");
    textBox3.SelectionStart = start;
    textBox3.SelectionLength = length;
}

Note: this is for Windows.Forms. I guess for wpf or asp or other ui frameworks the part with the cursor handling will differ.

0
fubo On

Here one approach

private void textBox3_TextChanged(object sender, EventArgs e)
{
    textBox3.Text = new string(textBox3.Text.Select(x => x == 'k' || x == 'K' ? 'k' : char.ToUpper(x)).ToArray());
}
1
Cleptus On

If you dont want to allow the user to enter invalid input, you can use the TextChanged event (other answers) or handle the KeyDown and KeyUp events. Check this link for that other approach.

https://msdn.microsoft.com/en-us/library/ms171537(v=vs.110).aspx

0
Ori Nachum On
  1. First, you keep the caret position - where your cursor is.
  2. Then, you calculate the new string - I extracted the condition in case it's not just 1 letter.
  3. Lastly, you save the new string, and return the caret to its position.

    private static bool CalculateConditionForLowerCase(string stringLetter)
    {
        return stringLetter.ToLower() == "k";
    }
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(textBox1.Text))
        {
            return;
        }
        var caretPosition = textBox1.SelectionStart;
        var sb = new StringBuilder();
        foreach (var letter in textBox1.Text)
        {
            var stringLetter = letter.ToString();
            sb.Append(CalculateConditionForLowerCase(stringLetter) ? stringLetter.ToLower() : stringLetter.ToUpper());
        }
        textBox1.Text = sb.ToString();
        textBox1.SelectionStart = caretPosition;
    }