Reputation: 1096
I have a label of size(47, 15) and my form size is(561, 270). When my label.text is so longer than the window size the last part of the text doesn't appear.How can i dynamically re-size the height and width of the label text with respect to my window.That is when the text is longer than the window then the text will be appear at some lines instead of one line. How can i do that????
Upvotes: 6
Views: 19835
Reputation: 1691
In my case I used TextRenderer.MeasureText
using System.Windows.Forms;
namespace MyApp.Views
{
public partial class test : Form
{
public Form1()
{
InitializeComponent();
//I am getting my dynamic content from a TextBox but you can get from any other source
string content = myTextBox.Text;
myDynamicSizeLabel.Text = content;
//calculating the height using TextRenderer.MeasureText and as reference the TextBox size
var height = TextRenderer.MeasureText(myTextBox.CreateGraphics(), myTextBox.Text, myTextBox.Font, myTextBox.Size, TextFormatFlags.WordBreak).Height;
//set the new size to my Label
myDynamicSizeLabel.Height = (height == 0 ? myDynamicSizeLabel.Height: height);
myDynamicSizeLabel.Width = myTextBox.Width;
//Autosize must be false
myDynamicSizeLabel.AutoSize = false;
}
}
}
It will produce a result like this
Upvotes: 0
Reputation: 1
i've been scratching my head to find a solution ..
use buttons instead of a label
additional... then if you want set flatstyle to flat ang make the boarder 0
Upvotes: -2
Reputation: 942267
One basic strategy is to set the MaximumSize.Width property so the label cannot grow horizontally beyond the window edge or overlap another control. It will now automatically wrap long text, adding lines vertically.
You may well also want to set the MaximumSize.Height property so the height cannot get out of control either. In which case you also want to set the AutoEllipsis property to True. So that the user can tell that the text was clipped and a ToolTip is automatically displayed when he hovers the mouse over the label.
Upvotes: 5