C# WinForms need to automatically align a set of labels inside a control in a simple topleft fashion

Go To StackoverFlow.com

0

I want to make a gui for what i explained here C# visual control for editing statements / equations / conditions?

Basically its an expression editor. Each expression consists of a list of stuff, which can be a text string or a parameter. For example, an expression:

If x is greater than 0

consists of:

String "If"
Parameter "variable" (= "x")
String "is"
Parameter "comparator" (= "greater than")
Parameter "value" (= "0")

So, when user wants to edit such expression, i must create (dynamically) five labels, and place them inside the control (Panel) and add onclick events to those of them that arent just strings, so that user can open a window to change the comparator or the variable name etc. The labels must obviously arrange themselves inside the control they are bound to.

Thing is, i dont know if there is already a way to do it automatically. I'd like those labels to arrange themselves just like the words arrange on this page. While it fits, put it to the right of the previous label, when it doesnt, put it on the start of the next row.

Do i have to manually move them OnResize() of the control they are in, or is there an automated way to do it?

Thanks!

2012-04-05 20:32
by Istrebitel


3

Try using a FlowLayoutPanel

//Sample:
//Assuming you are creating your labels from 
//List<string>



 List<string> labels=new List<string>();
    labels.Add("If");
    labels.Add("variable");
    labels.Add("=");
    labels.Add("5");
    for (int i = 0; i < labels.Count; i++)
    {
        Label lbl = new Label();
        lbl.Text = labels[i];
        flowLayoutPanel1.Controls.Add(lbl);
    }
2012-04-05 20:44
by Andrea Scarcella
Thank you, this is it - Istrebitel 2012-04-09 18:04


3

Take a look a the FlowLayoutPanel.

From the docs:

The FlowLayoutPanel control arranges its contents in a horizontal or vertical flow direction. Its contents can be wrapped from one row to the next, or from one column to the next. Alternatively, its contents can be clipped instead of wrapped.

2012-04-05 20:39
by heavyd
Thank you! I'll mark the other answer though because it contains code example - Istrebitel 2012-04-09 18:05
Ads