Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Textchanged event fires twice in a multiline TextBox

I have a very bizarre problem with the TextChanged event in a multiline TextBox (WinForms). it appears that the event fires twice under certain circumstances.

This complete code demonstrates the issue:

public partial class TextChangedTest : Form
{
    public TextChangedTest()
    {
        InitializeComponent();
    }

    private void TextChangedTest_Load(object sender, EventArgs e)
    {
        TextBox tb = new TextBox();
        //Remove the following line and the code behaves as expected
        tb.Multiline = true;
        this.Controls.Add(tb);
        tb.TextChanged += new EventHandler(tb_TextChanged);
    }
    private void tb_TextChanged(object sender,EventArgs e)
    {
        //Need to validate and use the new text here.
        //For testing, just use a MessageBox
        MessageBox.Show("Handler fired");
    }
}

If you now type a character in the TextBox, the event fires. Correct behaviour.

If you delete the character, the event fires once. Correct behaviour.

If you delete the character with backspace, the event fires once. Correct behaviour.

If you delete the character by selecting it and pressing Delete, the event fires once. Correct behaviour.

However

If you select the character and type another character, the event fires twice, once after the text box is cleared (look at the textbox when the first event fires) and once when the character is added. This behaviour is nonsense, if understandable.

This only happens when the Multiline property is set (which I am using to resize the TextBox). It just took me 5 hours to work that out!

My problem is that I have to validate each character in the TextChanged event, and I get invalid results.

Does anyone have any ideas?

I could possibly use the Keypress event, but I would need to do a lot of recoding to do that.

like image 824
Blind Fury Avatar asked Nov 09 '22 19:11

Blind Fury


1 Answers

The workaround for my particular case is even more bizarre.

I needed the Textbox to have a specific size, but the height cannot be changed unless it is multiline.

The following, however, works for me in my little world:

    tb.Multiline = true;
    tb.Size = new Size(x,y);
    tb.Multiline = false;
    this.Controls.Add(tb);
    tb.TextChanged += new EventHandler(tb_TextChanged);

Solution found at http://en.code-bude.net/tag/c-textbox-height-resize/

Doesn't resolve the underlying problem, though.

like image 158
Blind Fury Avatar answered Nov 15 '22 06:11

Blind Fury