Windows Develop Bookmark and Share   
 index > Windows Forms General > How to determine if any text fit to TextBox area or not?
 

How to determine if any text fit to TextBox area or not?


How to set TextBox.ScrollBars = Vertical when text doesn't fit in it?
Anatoly I  Thursday, April 17, 2008 7:57 PM

You may want to create your own version by iterating through the words, and splitting them apart. I tried to create something like this, and the code is below, but MeasureString doesn't seem to work properly. When I measure a particular string, it says that the string's length is wider than that of the textbox I'm referring to, however, the textfits into the box on the form just fine. This is a strange one indeed. Good luck, hopefully my code below can give you a jumping off point, but buyer beware, this is not fully tested code.

This link might also be more help than I can be:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3205677&SiteID=1

Code Snippet

public Size MeasureString(string text, Font font, int width, Graphics g)

{

SizeF result = new SizeF(0, 0);

int lastindex = 0;

int startindex = 0;

string previousstring = string.Empty;

while (-1 != text.IndexOf(' ', lastindex)) {

string substring = text.Substring(startindex, text.IndexOf(' ', lastindex) - startindex).Trim();

SizeF tempsize = g.MeasureString(substring, font);

if (tempsize.Width > width)

{

tempsize = g.MeasureString(previousstring, font);

startindex = text.LastIndexOf(' ', lastindex - 2);

result.Height += tempsize.Height - 1;

if (result.Width < tempsize.Width)

result.Width = tempsize.Width;

}

lastindex = text.IndexOf(' ', lastindex) + 1;

previousstring = substring;

}

return result.ToSize();

}

David M Morton  Sunday, April 20, 2008 10:57 PM

You could set the TextBox's ScrollBars property to Vertical, but the scrollbar would show up all the time.

Alternatively, you could use the RichTextBox control, which adds the scroll bar only when the text doesn't fit.

David M Morton  Thursday, April 17, 2008 8:05 PM
I'm gouing to use this feature for smart device application. So, I can't use the ReachTextBox - .NET Compact Framework doesn't support the control. And I would like to have TextBox.ScrollBars = Vertical set just when it really need.
Anatoly I  Saturday, April 19, 2008 1:25 PM

Ahh!!! You're using .NET Compact Framework. I did a little digging, and this is what I came up with. This should work for you, although you may want to adjust the size of the bitmap created by just a little bit to ensure that it accounts for the frame of the textbox control:

Code Snippet

string text = "My text to measure the size of...";

// create a new bitmap based on the width

// and height of the control. You may need

// to adjust this size just a bit to account

// for the frame size of the textbox control.

Bitmap b = new Bitmap(textBox1.Width, textBox2.Height);

// Create a graphics from the image.

// Unfortunately, you can't just create

// a graphics image from the TextBox by calling

// TextBox.CreateGraphics(), as this isn't

// available in .NET Compact Framework.

Graphics g = Graphics.FromImage(b);

// Measure the string text that you need to

// measure. The overload that takes the width

// will enable word wrapping for you.

Size s = g.MeasureString(text, textBox2.Font, b.Width).ToSize();

// See if the height of the measured

// string exceeds the height of the textbox.

// If so, set the ScrollBar to vertical.

// If not, set ScrollBar to None.

if (s.Height > textBox2.Height)

{

textBox2.ScrollBars = ScrollBars.Vertical;

}

else

{

textBox2.ScrollBars = ScrollBars.None;

}

// Put the text in the box.

textBox2.Text = text;

David M Morton  Saturday, April 19, 2008 4:58 PM
David, thanks for the thorough explanation!
But it seems to me, that just
Graphics.MeasureString (String, Font)
method is supported by the .NET Compact Framework.
Any idea?


Anatoly I  Sunday, April 20, 2008 4:39 PM

You may want to create your own version by iterating through the words, and splitting them apart. I tried to create something like this, and the code is below, but MeasureString doesn't seem to work properly. When I measure a particular string, it says that the string's length is wider than that of the textbox I'm referring to, however, the textfits into the box on the form just fine. This is a strange one indeed. Good luck, hopefully my code below can give you a jumping off point, but buyer beware, this is not fully tested code.

This link might also be more help than I can be:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3205677&SiteID=1

Code Snippet

public Size MeasureString(string text, Font font, int width, Graphics g)

{

SizeF result = new SizeF(0, 0);

int lastindex = 0;

int startindex = 0;

string previousstring = string.Empty;

while (-1 != text.IndexOf(' ', lastindex)) {

string substring = text.Substring(startindex, text.IndexOf(' ', lastindex) - startindex).Trim();

SizeF tempsize = g.MeasureString(substring, font);

if (tempsize.Width > width)

{

tempsize = g.MeasureString(previousstring, font);

startindex = text.LastIndexOf(' ', lastindex - 2);

result.Height += tempsize.Height - 1;

if (result.Width < tempsize.Width)

result.Width = tempsize.Width;

}

lastindex = text.IndexOf(' ', lastindex) + 1;

previousstring = substring;

}

return result.ToSize();

}

David M Morton  Sunday, April 20, 2008 10:57 PM
Thanks David!
I will study you wrote.
Anatoly I  Monday, April 21, 2008 8:06 PM
Hi David!
I've found a few mistakes in your code. It didn't count height of the first string and tooke into account last word in each string twice.
But it was very helpful for me!
I realized your idea in my own manner.

private int MeasureString(string text, Font font, int width, Graphics g)
{
string[] split = text.Split(new Char[] { ' ' });
List<string> SplitList = new List<string>();
foreach (string s in split)
if (s.Trim() != "")
SplitList.Add(s);
string previousString = "";
string currentString = "";
float result = g.MeasureString(SplitList[0], font).Height;
SizeF tempSize = new SizeF(0, 0);
//List<string> testList = new List<string>();
foreach (string s in SplitList)
{
currentString += " ";
currentString += s;
tempSize = g.MeasureString(currentString, font);
if (tempSize.Width > width)
{
tempSize = g.MeasureString(previousString, font);
result += tempSize.Height - 2;
//testList.Add(previousString + " " + tempSize.Height);
currentString = s;
}
previousString = currentString;
}
return (int)result;
}
Anatoly I  Thursday, April 24, 2008 6:49 PM
Hi,

Well, the above method does not work for all situations. For example if the text contains "New Line, i.e. ENTER" in various forms like:

This is test.

*AAA
*BBB

*CCC
*DDD
-----------------------------------------------------------------------------------------------------------------------------------------------------------
So, here's a proposed solution based on:
1. Working smart and not hard.
2. Reusability.
3. Not re-inventing the wheel.

Here's isa self explanatory method:

        /// <summary>
        /// Purpose: To show vertical scrolling in a Textbox if required, having fixed Width.
        /// Logic: Use a Label-control for reference. 
        ///        Fix Label's MinumumSize, same as the width and height of the Textbox.
        ///        Fix Label's MaximumSize(Width), same as the width of the Textbox so that width does not increase.
        ///        Assign Label's MaximumSize(Height), to be far greater than the Height of Textbox.
        ///        Set Label's Text, same as Textbox's Text.
        ///        Now, the Label would resize itself. 
        ///        So, by comparing the heights of Label and Textbox, we can identify if vertical scollbar in Textbox is required or not.
        /// </summary>
        /// <param name="txtToCheck">Textbox where vertical scrolling is to be shown if required.</param>
        private void ShowVerticalScroll(TextBox txtToCheck)
        {
            try
            {
                Label lblPrototype = new Label();

                lblPrototype.AutoSize = true;
                lblPrototype.Font = txtToCheck.Font;
                lblPrototype.BorderStyle = BorderStyle.FixedSingle;
                lblPrototype.MinimumSize = new Size(txtToCheck.Width, txtToCheck.Height);
                lblPrototype.MaximumSize = new Size(txtToCheck.Width, txtToCheck.Height * 10);

                lblPrototype.Text = txtToCheck.Text;

                if (lblPrototype.PreferredHeight > txtToCheck.Height)
                {
                    txtToCheck.ScrollBars = ScrollBars.Vertical;
                }
                else
                {
                    txtToCheck.ScrollBars = ScrollBars.None;
                }
            }
            catch (Exception ex)
            {
                ex = new Exception("Error occurred while deciding vertical scroll for Textbox. " + ex.Message);
                throw ex;
            }
        }
:)
Lakra
Abhijeet Lakra  Monday, April 06, 2009 9:49 AM
I think is enought to set the textbox' Multiline property to true
Best regards, Sergiu
Sergiu Dudnic  Monday, April 06, 2009 11:18 AM

Well, the requirement is to show Scroll baronly ifneeded i.e. if the entire text cannotfit in the Textbox' Area.
If the text is small enough to fit in the Textbox' area, vertical scroll baris not to be shown.

Secondly, the above mentioned method also forms the basis to dynamically increase or reduce the font size of Textbox to fit inside the given Textbox' area.

Multiline property always shows a vertical scroll bar(Enabled or Disabled). So, it does not solve the purpose.


Regards, Lakra :)
Abhijeet Lakra  Tuesday, April 07, 2009 12:37 AM
@Abhijeet Lakra: You apparently missed the fact that the OP is on the compact framework. AutoSize, MinimumSize, MaximumSize are not available there.
Andreas Huber  Monday, September 21, 2009 11:19 AM

You can use google to search for other answers

Custom Search

More Threads

• having trouble running application over network but works locally
• Show picture in Gridview
• Using the Windows password in my application
• Prevent multiple instances of MdiChild form?
• How to change Theme for desktop application
• .Focus() method
• How to use MeasureCharacterRanges?
• flowLayoutPanel and scrollBar
• What logical order are Controls stored in the Controls collection?
• ASP.NET Web Application on Linux Server