vendredi 8 mai 2015

Text vanishing in Winforms Textbox

I'm running into a strange issue with a WinForms textbox. When I set the Text property to a long string, the text seems to vanish. My understanding is that a textbox in Winforms has a default MaxLength of 32767, which can be set to any value less than or equal to int.MaxValue. The steps to reproduce the issue are as follows:

  1. Fire up Visual Studio 2013
  2. Create a new Windows Form Application. Choose to target the .NET 3.5 framework.
  3. Drag a textbox control onto the form.
  4. In the form load event, type in the following code:

    private void Form1_Load(object sender, EventArgs e)
    {
        // Setting the MaxLength property should be unnecessary since the
        // default is 32767, but I'm implicitly setting it anyway.
        textBox1.MaxLength = int.MaxValue;
        string s = "";
    
        // Weird things happen when the value in the next line
        // is set to anything >= 4680
        for (int i = 0; i < 15000; i++)
        {
            s = s + "A";
        }
    
        textBox1.Text = s;
    }
    
    

Run this application and you'll that the textbox "appears" empty. I say "appears" because if you put your cursor in the textbox, you can see that it behaves as though something is in the textbox, but nothing is there visually.

Whatever is going on, 4680 seems to be the "magic number". If you change the number in the for loop to 4680, you still get no text in the textbox (although clicking in the textbox will make the text show up). If you change it to 4679 or anything smaller, then it works just fine.

Does anyone have any ideas or workarounds for this odd behavior?

Aucun commentaire:

Enregistrer un commentaire