Search code examples
c#visual-studiolinklabel

FormLayoutPanel, Not Changing Direction when using LinkLabels


I'm trying to use the FlowLayoutPanel with linkLabels in Visual Studio for a quick project. I've selected "TopDown" for direction and wrapping to false. When I launch the program; however, the direction always shows left to right. Is there a box or something that I haven't checked? Or is there any reason a linklabel would ignore the flow direction?

Here's my code and some screenshots of what I see.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace myProject
{
public partial class Form1 : Form
{
    FlowLayoutPanel panel = new FlowLayoutPanel();


    public Form1()
    {
        InitializeComponent();

        linkLabel1.LinkClicked += linkLabel1_LinkClicked;
        linkLabel2.LinkClicked += linkLabel2_LinkClicked;
        linkLabel3.LinkClicked += linkLabel3_LinkClicked;

        Controls.Add(panel);
        panel.Controls.Add(linkLabel1);
        panel.Controls.Add(linkLabel2);
        panel.Controls.Add(linkLabel3);
    }

    private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        panel.Controls.SetChildIndex(linkLabel1, 0);
    }

    private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        panel.Controls.SetChildIndex(linkLabel2, 0);
    }

    private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        panel.Controls.SetChildIndex(linkLabel3, 0);
    }


  }
}

This is the control view before I've started the program. This is the control view before I've started the program.

This is what I see when I run the program - marked with the red arrow. enter image description here


Solution

  • Because you are initializing your FlowLayoutPanel in the code-behind, you have to set the FlowDirection property of this new instance of FlowLayoutPanel in the same code-behind:

        FlowLayoutPanel panel = new FlowLayoutPanel();
        public Form1()
        {
            InitializeComponent();
            panel.FlowDirection = FlowDirection.TopDown;
    

    The FlowLayoutPanel that you declare in your code-behind is separate from the one you have in your layout, so the FlowDirection property is not set the same. I tested the code above and I believe it does what you were looking for.