Word wrap for a label in Windows Forms - c#

How can one get word wrap functionality for a Label for text which goes out of bounds?

Actually, the accepted answer is unnecessarily complicated.
If you set the label to AutoSize, it will automatically grow with whatever text you put in it. (This includes vertical growth.)
If you want to make it word wrap at a particular width, you can set the MaximumSize property.
myLabel.MaximumSize = new Size(100, 0);
myLabel.AutoSize = true;
Tested and works.

The quick answer: switch off AutoSize.
The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic.
Basically what you need to do in OnPaint is:
Measure the height of the text (Graphics.MeasureString).
If the label height is not equal to the height of the text set the height and return.
Draw the text.
You will also need to set the ResizeRedraw style flag in the constructor.

In my case (label on a panel) I set label.AutoSize = false and label.Dock = Fill.
And the label text is wrapped automatically.

There is no autowrap property but this can be done programmatically to size it dynamically. Here is one solution:
Select the properties of the label
AutoSize = True
MaximumSize = (Width, Height) where Width = max size you want the label to be and Height = how many pixels you want it to wrap

From MSDN, Automatically Wrap Text in Label:
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
public class GrowLabel : Label {
private bool mGrowing;
public GrowLabel() {
this.AutoSize = false;
}
private void resizeLabel() {
if (mGrowing)
return;
try {
mGrowing = true;
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height;
}
finally {
mGrowing = false;
}
}
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
resizeLabel();
}
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
resizeLabel();
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
resizeLabel();
}
}

I had to find a quick solution, so I just used a TextBox with those properties:
var myLabel = new TextBox
{
Text = "xxx xxx xxx",
WordWrap = true,
AutoSize = false,
Enabled = false,
Size = new Size(60, 30),
BorderStyle = BorderStyle.None,
Multiline = true,
BackColor = container.BackColor
};

Have a better one based on #hypo 's answer
public class GrowLabel : Label {
private bool mGrowing;
public GrowLabel() {
this.AutoSize = false;
}
private void resizeLabel() {
if (mGrowing)
return;
try {
mGrowing = true;
int width = this.Parent == null ? this.Width : this.Parent.Width;
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height + Padding.Bottom + Padding.Top;
} finally {
mGrowing = false;
}
}
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
resizeLabel();
}
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
resizeLabel();
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
resizeLabel();
}
}
int width = this.Parent == null ? this.Width : this.Parent.Width; this allows you to use auto-grow label when docked to a parent, e.g. a panel.
this.Height = sz.Height + Padding.Bottom + Padding.Top; here we take care of padding for top and bottom.

Put the label inside a panel
Handle the ClientSizeChanged event for the panel, making the
label fill the space:
private void Panel2_ClientSizeChanged(object sender, EventArgs e)
{
label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
}
Set Auto-Size for the label to true
Set Dock for the label to Fill
All but step 2 would typically be done in the designer window.

Not sure it will fit all use-cases but I often use a simple trick to get the wrapping behaviour:
put your Label with AutoSize=false inside a 1x1 TableLayoutPanel which will take care of the Label's size.

Set the AutoEllipsis Property to 'TRUE' and AutoSize Property to 'FALSE'.

If your panel is limiting the width of your label, you can set your label’s Anchor property to Left, Right and set AutoSize to true. This is conceptually similar to listening for the Panel’s SizeChanged event and updating the label’s MaximumSize to a new Size(((Control)sender).Size.Width, 0) as suggested by a previous answer. Every side listed in the Anchor property is, well, anchored to the containing Control’s respective inner side. So listing two opposite sides in Anchor effectively sets the control’s dimension. Anchoring to Left and Right sets the Control’s Width property and Anchoring to Top and Bottom would set its Height property.
This solution, as C#:
label.Anchor = AnchorStyles.Left | AnchorStyles.Right;
label.AutoSize = true;

If you really want to set the label width independent of the content, I find that the easiest way is this:
Set autosize true
Set maximum width to how you want it
Set minimum width identically
Now the label is of constant width, but it adapts its height automatically.
Then for dynamic text, decrease the font size. If necessary, use this snippet in the sub where the label text is set:
If Me.Size.Height - (Label12.Location.Y + Label12.Height) < 20 Then
Dim naam As String = Label12.Font.Name
Dim size As Single = Label12.Font.SizeInPoints - 1
Label12.Font = New Font(naam, size)
End If

This helped me in my Form called InpitWindow:
In Designer for Label:
AutoSize = true;
Achors = Top, Left, Right.
private void InputWindow_Shown(object sender, EventArgs e) {
lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left - btOK.Margin.Right -
lbCaption.Margin.Right - lbCaption.Margin.Left,
Screen.GetWorkingArea(this).Height / 2);
this.Height = this.Height + (lbCaption.Height - btOK.Height - btCancel.Height);
//Uncomment this line to prevent form height chage to values lower than initial height
//this.MinimumSize = new Size(this.MinimumSize.Width, this.Height);
}
//Use this handler if you want your label change it size according to form clientsize.
private void InputWindow_ClientSizeChanged(object sender, EventArgs e) {
lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left * 2 - btOK.Margin.Right * 2 -
lbCaption.Margin.Right * 2 - lbCaption.Margin.Left * 2,
Screen.GetWorkingArea(this).Height / 2);
}
Whole code of my form

If the dimensions of the button need to be kept unchanged:
myButton.Text = "word\r\nwrapped"

The simple answer for this problem is to change the DOCK property of the Label. It is "NONE" by default.

If you are entering text into the label beforehand, you can do this.
In the designer,
Right-Click on the label and click Properties.
In Properties, search for text tab.
Click in the tab and click on the arrow button next to it.
A box will popup on top of it.
You can press enter in the popup box to add lines and type as in notepad!
(PRESS ENTER WHERE YOU WANT TO WRAP THE LABEL TEXT)

I would recommend setting AutoEllipsis property of label to true and AutoSize to false. If text length exceeds label bounds, it'll add three dots (...) at the end and automatically set the complete text as a tooltip. So users can see the complete text by hovering over the label.

I have a label that autowraps and grows to whatever size in a right docked autosize panel, whose width is set by other content.
Label (in tablelayoutpanel) Autosize = True.
TableLayoutPanel (in panel) Autosize = True, AutoSizeMode = GrowAndShrink, Dock = Bottom, one Column SizeType = 100%, one Row SizeType = 100%.
Panel (right docked in form) AutoSize = True, AutoSizeMode = GrowAndShrink, Dock = Right.

Use System.Windows.Forms.LinkLabel instead of Label and set the property LinkArea as below.
myLabel.LinkArea = new LinkArea(0, 0);

Use style="overflow:Scroll" in the label as in the below HTML. This will add the scroll bar in the label within the panel.
<asp:Label
ID="txtAOI"
runat="server"
style="overflow:Scroll"
CssClass="areatext"
BackColor="White"
BorderColor="Gray"
BorderWidth="1"
Width = "900" ></asp:Label>

Related

Location of panel not correct when using different anchor style

this is for Winforms / C# btw.
So I am making my own ComboBox, just playing around.
The item List is basically a Panel, which is located under or above the ComboBox control, depending on its height and location.
This works as intended, as long as I use AnchorStyle Top / Left for my usercontrol.
As soon as I switch to Top / Right Style, the location of my listpanel breaks. Okay, makes sense, the location point of my usercontrol changes with the different anchorstyle, so how about I adjust my panel to a new location using my usercontrol.LocationChanged event? Doesen't work. Maybe because of the order of the events? Or does the origin of locations change depending on the given AnchorStyles?
Anyway, I am a bit lost. Unfortunately I couldn't find a similar case here, therefore this question.
Here's my DropDownPanel (effectively my "list"):
private Panel DropDownPanel()
{
Panel DropDownPanel = new Panel() {
Width = this.Width,
Height = 200,
BackColor = _skin.TextBoxBackColor,
BorderStyle = BorderStyle.FixedSingle,
ForeColor = _skin.TextBoxForeColor,
Visible = false,
AutoScroll = false
};
DropDownPanel.HorizontalScroll.Enabled = false;
DropDownPanel.HorizontalScroll.Visible = false;
DropDownPanel.HorizontalScroll.Maximum = 0;
DropDownPanel.AutoScroll = true;
DropDownPanel.Leave += DropDownPanel_Leave;
return DropDownPanel;
}
Here's my userControl Load Event:
private void GbComboBox_Load(object sender, EventArgs e)
{
_dropDownPanel = DropDownPanel();
this.Parent.Parent.Controls.Add(_dropDownPanel);
RelocateDropDownPanel();
_dropDownPanel.BringToFront();
ApplyItems(_items);
}
And my calculation for the location:
private void RelocateDropDownPanel()
{
if (_dropDownPanel != null)
{
int initLocY = this.Parent.Location.Y + this.Location.Y + this.Height + _dropDownPanel.Height;
int fullHeight = this.FindForm().Height;
Point p = new Point();
if (initLocY < fullHeight)
{
p = new Point(this.Parent.Location.X + this.Location.X, initLocY - _dropDownPanel.Height);
}
else
{
p = new Point(this.Parent.Location.X + this.Location.X, initLocY - _dropDownPanel.Height - this.Height);
}
_dropDownPanel.Location = p;
}
}
So I figured out a "solution".
I simply inherited the Anchor of my Panel from the Usercontrol it was associated to.
But I wanna mention, that still, this whole thing is kind of a crappy way of dealing with custom combobox desings. As #Jimi stated in his first comment, the correct way of doing this would be to ownerdraw the combobox. I haven't done this because of specific reasons, which didn't let me do this.
A little example on how this could be made:
Change ComboBox Border Color in Windows Forms

DataGridView Auto Height - How to AutoSize DataGridView Height?

I am trying to make the height of my DataGridView AutoSize based on the amount of rows it contains. Currently, I was able to accomplish this with the following line:
dataGridView_SearchResults.AutoSize = true;
However this makes the Horizontal scroll bar disappear, the the DataGridView gets cut off.
How can I autosize the height without losing the horizontal scroll bar?
Option 1 - Overriding GetPreferredSize
You can override GetPreferredSize method of DataGridView and call the base method using new proposed size new Size(this.Width, proposedSize.Height). This way, the current width of control will remain untouched while the auto-size rules will apply on its height:
using System.Drawing;
using System.Windows.Forms;
public class MyDataGridView : DataGridView
{
public override Size GetPreferredSize(Size proposedSize)
{
return base.GetPreferredSize(new Size(this.Width, proposedSize.Height));
}
}
Option 2 - Setting the Height based on Height of Calculated Auto-Size
If you don't want to derive from DataGridView, you can calculate the auto-size by calling its GetPreferredSize passing new Size(0, 0) then set the height of DataGridView to the height of result, this way you only change the height of DataGridView. You should set the auto-height in RowsAdded, RowsRemoved, some other events if you need:
void AutoHeightGrid(DataGridView grid)
{
var proposedSize = grid.GetPreferredSize(new Size(0, 0));
grid.Height = proposedSize.Height;
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.RowsAdded += (obj, arg) => AutoHeightGrid(dataGridView1);
dataGridView1.RowsRemoved += (obj, arg) => AutoHeightGrid(dataGridView1);
//Set data source
//dataGridView1.DataSource = something;
}
If you want to make sure that all changes in grid including changing Font, height of rows will cause resizing grid, you can call the method in Paint event.
Option 3 - Setting MaximumSize
Also as mentioned by Hans, if you don't want to derive from DataGridView, you can use MaximumSize property of the grid. You can set it to new Size(this.dataGridView1.Width, 0):
dataGridView1.MaximumSize = new Size(this.dataGridView1.Width, 0);
dataGridView1.AutoSize = true;
Note
Since using MaximumSize is not so friendly when the user wants to let the grid width change by left and right anchors, I prefer to use Option 1 or Option 2.
I tried every option proposed by Reza Aghaei using .NET Framework 4.7.2. All the times I got an extra space between the last row and the DataGridView bottom border. So I tried a different approach, and it works!
Using the event you prefer, write the following line:
dataGridView1.Height = DataGridView1.Rows.GetRowsHeight(DataGridViewElementStates.Visible)
+ (dataGridView1.ScrollBars.HasFlag(ScrollBars.Horizontal) ? SystemInformation.HorizontalScrollBarHeight : 0)
+ 3;
You'd change the last +3 according to the style of your choice. Just change it from +1 to +5 depending of your likes.

How to hide and show panels on a form and have it resize to take up slack?

I have a form with three panels.
I want the top two to be a fixed height, and bottom one to fill the rest of the space.
The dialog is resizable, so all should change width on resixze, and bottom one should change height.
This is important, the user must be able to stretch the form, as well as the program through code.
If I set a panel to visible = false, I want the form height to shrink so the others stay the same height.
If I set a panel to visible = true, I want the form height to grow by the height of the panel.
I will control the hiding/showing of the panels with buttons. The idea is I show certain panels for "advanced" mode in my form, and hide them for "simple" mode. I cannot have a bunch of blank space if I hide a panel, and I want the form to shrink a bunch for simple mode.
I tried doing this with panels docked to top, but a form resize by the user will not change a panel height. So that is the main trick I am asking for help on.
Anyone in this kind of situation can use the below styling:
Use 2-3 Panel to Group different Controls and place them in a single parent control say a GroupBox.
Make all the child panels Dock to the same side say "Top".
if any of the panel is jumping over another due to similar docking. In Visual Studio, go to menu View > Other Windows > Document Outline and Set the display order. (https://msdn.microsoft.com/en-us/library/46xf4h0w%28v=vs.80%29.aspx)
Set the Panel property as follows:
AutoSize: true
AutoSizeMode: GrowAndShrink
Once the panel is not visible, other panel will take away the empty space.
Hope this helps!!!
the other posts are close, there is a detail missing that I included in the solution I came up with. Its a flag to tell if the sized event was caused by a user form resize, or the program doing it when a panel is shown or hidden.
For this solution, make a form with 4 panels.
Set dock to top for all panels. Do not set any autosizing for panels or form.
Also make two buttons and place on top panel, or any panel that you will not be hiding.
The code below shows how to handle the resized event, and the showing hiding buttons.
I made them hide/show panel 2, but the code should work for any panel.
namespace ProgTesting {
public partial class Form5 : Form {
private bool doNothing = false;
public Form5() {
InitializeComponent();
cmdAdvanced.Visible = false;
}
private void cmdSimple_Click(object sender, EventArgs e) {
if (panel2.Visible) {
panel2.Visible = false;
doNothing = true;
this.MinimumSize = new Size(this.Width, this.Height - panel2.Height);
this.Height = this.Height - panel2.Height;
doNothing = false;
cmdSimple.Visible = false;
cmdAdvanced.Visible = true;
}
}
private void cmdAdvanced_Click(object sender, EventArgs e) {
if (!panel2.Visible) {
panel2.Visible = true;
doNothing = true;
this.Height = this.Height + panel2.Height;
this.MinimumSize = new Size(this.Width, this.Height);
doNothing = false;
cmdAdvanced.Visible = false;
cmdSimple.Visible = true;
}
}
private void Form5_SizeChanged(object sender, EventArgs e) {
if (!doNothing)
if (panel2.Visible)
panel3.Height = this.ClientSize.Height - panel1.Height - panel2.Height - panel4.Height;
else
panel3.Height = this.ClientSize.Height - panel1.Height - panel4.Height;
}
}
}
You do have to manage the heights going on, which is a pain but gives you control. Some shots of it working:
It sounds like what you are looking for is an Expander. Essentially a control that consists of a header and a content area, where clicking on the header toggles the content area between visible and collapsed.
I'm not 100% certain if an Expander control will automatically adjust the height of a form when it expands/collapses though. You may need to hook up an event handler to the Expander to manually adjust the height of your form when the Expander collapses.
Try looking at the Stack Overflow Question Add an expander (collapse/expand) to a Panel WinForm. There are a number of links from that question about implementing an Expander in Windows Forms, including some that provide full source code.
Update:
I've knocked up a quick demo that will accomplish what you want, in a very primitive way, not using any of the various Expander controls out there. I think that while you will find the Expanders useful, I doubt they will adjust the size of the container they are inside, unless you write some adjustment code like I have below.
Create a form that looks like this:
The two text boxes are anchored Left, Top, Right.
The toggle button is anchored Left, Top, named btnTogglePanel.
The magenta panel is anchored Left, Top, Right, Bottom, named pnlToggled.
The bottom button is anchored Right, Bottom.
Then in the code behind for the form:
public partial class ToggleableExpanderForm : Form
{
public ToggleableExpanderForm()
{
InitializeComponent();
SizeChanged += (s, args) =>
{
if (_LastSize.HasValue)
{
var diff = Size - _LastSize.Value;
if (_LastHeight.HasValue
&& !IgnoreNextResizeForLastHeightAdjustment)
{
_LastHeight += diff.Height;
}
}
_LastSize = Size;
};
}
private Size? _LastSize;
private bool IgnoreNextResizeForLastHeightAdjustment = true;
private int? _LastHeight;
private void btnTogglePanel_Click(object sender, EventArgs e)
{
var newVisibility = !pnlToggled.Visible;
int heightAdjustment = 0;
if (newVisibility)
{
if (_LastHeight.HasValue)
{
heightAdjustment = _LastHeight.Value;
_LastHeight = null;
}
}
else
{
_LastHeight = pnlToggled.Height;
heightAdjustment = -pnlToggled.Height;
}
pnlToggled.Visible = newVisibility;
IgnoreNextResizeForLastHeightAdjustment = true;
Height += heightAdjustment;
}
}
Essentially you adjust the height of the form manually when the toggle button is clicked, based on whether or not the panel is hiding/showing. You also need to take into account of what will happen when the user resizes the form when the panel is invisible, which is where the cruft around listening to the SizeChanged event comes in. You need the answer to "how MUCH has the size changed" and then you adjust your previously stored panel height as appropriate.
I don't imagine the above code is perfect, and I haven't tested it in every use case, but it gets the basic job done.
One way to go about it is to use a TableLayoutPanel for the top two panels.
The steps below will give you the resizing desired when the user resizes the form.
Start by created a TableLayoutPanel (TLP) and shrink it down from the default 2 columns, 2 rows to just 2 columns, 1 row.
Anchor it to Top, Left, and Right
Now size the TLP to fit your top two panels and place each panel in a cell of the TLP.
Anchor these two panels to all sides.
Position the 3rd panel (Panel3) below the TLP to your liking and anchor it to all sides.
To handle the hiding of Panel3 some logic will need to be added to the appropriate button_Click event. Determine what size you would like the "minimized" height to be and then just store the form size when Panel3 is visible and restore the height when it's clicked again. It should look something like this.
private void button1_Click(object sender, EventArgs e)
{
if (panel3.Visible)
{
// make invisible
panel3.Visible = false;
// storedHeight is a private member of the Form
storedHeight = Form1.ActiveForm.Height;
Form1.ActiveForm.Height = minimumHeight; // Set to predetermined minimum height
}
else
{
// make visible
panel3.Visible = true;
Form1.ActiveForm.Height = storedHeight;
}
}
Now when you hide Panel3 the form will shrink to the size of the TLP, then grow again when Panel3 is visible. Also the top panels will expand in width, but not height. You will need to change the MinSize properties of the form and its value will have to be dynamically adjusted depending on whether Panel3 is visible or not.

How to make Tab pages' widths fit into the TabControl's width

I have a TabControl with two tab pages.
How can I make the tab pages fit into the width of the TabControl like shown in the below screenshot.
I tried with the following line of code but it does not work either.
tabControl1.SizeMode = TabSizeMode.FillToRight;
First, set your tabControl1 size mode:
tabControl1.SizeMode = TabSizeMode.Fixed;
Then you have to recalculate width of the tab page header:
tabControl1.ItemSize = new Size(tabControl1.Width / tabControl1.TabCount, 0);
Pay attention: 1. value 0 means that height will be default. 2. Recalculate item size after you had added tab page to tab control. Consider what happens when you resize the control.
Contributing based on Jarek's answer. If you want tabs widths to change dynamically as you resize the TabControl as well, you can achieve this by implementing this on the TabControl Resize Event:
private bool doNotExecuteResizeEventAgain = true;
private void Tab_Control_Resize(object sender, EventArgs e)
{
if(doNotExecuteResizeEventAgain)
{
int tabWidth = ((int)(tab_Control.Width/tab_Control.TabPages.Count)) - 1;
doNotExecuteResizeEventAgain = false;
tab_Control.ItemSize = new Size(tabWidth, tab_Details.ItemSize.Height);
doNotExecuteResizeEventAgain = true;
}
}
The use of the variable doNotExecuteResizeEventAgain is because the ItemSize calls again the event Resize, so in order to stop it from cycling, I added that flag.
Use SizeMode on the TabControl: http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.sizemode.aspx
this is illegal way to solve this kind of issue
Increase the padding (X,Y)
X 100 // represent some allowed figures
Y 3 // represent some allowed figure.

Can StatusStrip automatically change its height depending on its items' size?

I've got a statusstrip with a number of items. One of them is a ToolStripStatusLabel with Spring = True.
When the text of the label is too long, one can't see it.
Is it possible to make the statusstrip become higher and show whole text in multiline?
This is an interesting problem....I tried a couple of things but no success...basicall the ToolStripStatusLabel is very limited in capability.
I ended up trying a hack that gives the result you want but am not sure even I would recommend this unless of course this is absolutely necessary...
Here's what I have got...
In the properties of your StatusStrip set AutoSize = false, this is to allow the StatusStrip to be resized to accommodate multiple lines. I am assuming statusStrip called ststusStrip1 containing label called toolStripStatusLabel1.
At form Level declare a variable of TextBox type:
TextBox txtDummy = new TextBox();
At Form Load set some of its properties:
txtDummy.Multiline = true;
txtDummy.WordWrap = true;
txtDummy.Font = toolStripStatusLabel1.Font;//Same font as Label
Handle the paint event of the toolStripStatusLabel1
private void toolStripStatusLabel1_Paint(object sender, PaintEventArgs e)
{
String textToPaint = toolStripStatusLabel1.Tag.ToString(); //We take the string to print from Tag
SizeF stringSize = e.Graphics.MeasureString(textToPaint, toolStripStatusLabel1.Font);
if (stringSize.Width > toolStripStatusLabel1.Width)//If the size is large we need to find out how many lines it will take
{
//We use a textBox to find out the number of lines this text should be broken into
txtDummy.Width = toolStripStatusLabel1.Width - 10;
txtDummy.Text = textToPaint;
int linesRequired = txtDummy.GetLineFromCharIndex(textToPaint.Length - 1) + 1;
statusStrip1.Height =((int)stringSize.Height * linesRequired) + 5;
toolStripStatusLabel1.Text = "";
e.Graphics.DrawString(textToPaint, toolStripStatusLabel1.Font, new SolidBrush( toolStripStatusLabel1.ForeColor), new RectangleF( new PointF(0, 0), new SizeF(toolStripStatusLabel1.Width, toolStripStatusLabel1.Height)));
}
else
{
toolStripStatusLabel1.Text = textToPaint;
}
}
IMP: Do not assign the text property of your label instead put it in Tag we would use it from Tag
toolStripStatusLabel1.Tag = "My very long String";

Categories