Just now I saw a problem: StringBuilder Won't Show In TextBox (WinForms, C#). The author of the post could not display his content, which is a string of around 50k characters, in his single-line TextBox
.
The answer pointed out that he should change the MultiLine
property to true
. An explanation gave in the comment stated:
Since the iteration is 10000 times, the string generated is large and is not getting displayed in a single line textbox.
So I'm curious about the max length a single line text box can display.
I browsed SO and found this question: TextBox maximum amount of characters (it's not MaxLength), it clears some doubt, but not all. I still want to know:
- Since
Text
property are ofString
type, why it could not even handle 50k characters whenMultiLine
isfalse
? - How many characters a
TextBox
can hold whenMultiLine
isfalse
? Do we have a way to get this number? - Why
MultiLine
property affects this capability?
For question 2 first part, I did the following things to verify:
I suspected this length was related to the memory allocated to Text
property. I did some research online, and this MSDN Documentation gave me some insights:
Windows NT 4.0, Windows 2000, Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, Windows XP Home Edition, Windows XP Professional x64 Edition, Windows Server 2003 Platform Note: If the MaxLength property is set to 0, the maximum number of characters the user can enter is 2147483646 or an amount based on available memory, whichever is smaller.
So I did an experiment: I created 2 TextBox
, namely textBox1
and textBox2
. textBox2
will display the real time character count of textBox1
. In addition, I changed the MaxLength
property to 0
for both TextBox
. The code looks like this:
public Form1()
{
InitializeComponent();
textBox1.TextChanged += (s, e) => textBox2.Text = textBox1.Text.Length.ToString();
}
It turned out that when the length of text exceeds 43679
, the Text
completely gone:
So it seems the memory allocated to Text
property can hold upon 43679 characters on my computer. But I'm not sure if this number is the same for all computers. Do we have a way more sophisticate way to get this number?
Thanks in advance!
From my tests I find that a Textbox can't display lines that would exceed 32k pixels given the Font of the TextBox.
Using this little testbed
You can see that the display vanishes once the width would exceed 32k. For the chosen big Fontsize this happens with only about 1350 characters. This should explain our different results from the comments, imo.
The Text still holds the full length of the data.
Update: Acoording to the answers in this post this limit is not so much about TextBoxes and their Lines but about Windows Controls in general:
Hans Passant writes:
So when calculating its display, the TextBox hits that limit and silently/gracfully(??) doesn't display anything at all.