views:

110

answers:

2

hi

how to do this:

when i'll press 'G' on textbox in my form i'll see 'A' ?

in C# code (windows-CE or Windows-mobile)

thank's in advance

+4  A: 

I think you should handle the KeyPress event. Check if the key pressed is G, if yes, reject the input and put A in the textbox. Try this (The character will be appended to existing text:

    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        if (e.KeyChar == 'G')
        {
            // Stop the character from being entered into the control
            e.Handled = true;
            textBox1.Text += 'A';
        }
    }
Sidharth Panwar
Instead of `textBox1.Text += 'A';` i would prefer `textBox1.AppendText("A");`
Oliver
@Oliver Any specific reason?
Sidharth Panwar
@Sidharth: Performance. Just put 10,000 chars into your textBox and let a timer add a random char every 100ms. In the first test use the `+=` approach. In the second the `AppendText()` solution. The problem is that a string is immutable and so the whole string will be taken out of the textbox a single char appended and this whole string will be given back to the TextBox. This tells the Box to throw away its whole content and take the new one, thous leading to nasty flickering.
Oliver
Wouldn't there be better my approach?
Juan Nunez
+12  A: 
    TextBox t = new TextBox();
    t.KeyPress += new KeyPressEventHandler(t_KeyPress);


    void t_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == 'G')
            e.KeyChar = 'A';
    }
Juan Nunez
This is more elegant :) - +1
Sidharth Panwar