views:

51

answers:

2

Hi,

I have a textbox, nothing surprising there. When the text is changed I call the change event and put everything in that text box to uppercase characters using .upper(). However, the textbox always puts the cursor to the beginning of the text box. So for example lets say you type in abc it will actually appear in the box as CBA as the cursor always seems to stay, unless you use the arrow keys at the beginning of the text box, why is this and how do you correct it?

collector_initials.Text = collector_initials.Text.ToUppper();

Thanks r.

A: 

Save the current index before changing the text:

int savedIndex = textbox.SelectionStart;

Set it again after changing the text:

// you will have to decide what to do if your index is larger than the text length
textbox.SelectionStart = Math.Min( savedIndex, textbox.Text.Length );
textbox.SelectionLength = 0;
Ed Swangren
+1  A: 

Setting the Text property resets the TextBox.SelectionStart and SelectionLength properties. Changing the insert point in the process. There's a better mousetrap available here, implement the KeyPress event so you can modify the pressed key. Like this:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
        e.KeyChar = char.ToUpper(e.KeyChar);
    }
Hans Passant
Thanks you, that was exactly the answer I was looking for :)
flavour404