How to Move Controls at RunTime in a flowLayoutPanel Control?

Hi

How to Move Controls at RunTime inside the same flowLayoutPanel Control by using Drag-n-Drop

Thanks

Deza



Answer this question

How to Move Controls at RunTime in a flowLayoutPanel Control?

  • Andrej Burger

    Thanks a lot!

    It is exactly what I needed

    Deza


  • tbthtbth

    Hi Deza,

    Here are the basic steps:

    1) Dragdrop requires handling specific type names. Since your FlowLayoutPanel is likely to have multiple types, the easiest way is to use a wrapper to reduce all types to one. This way you avoid having to use extensive if then constructions. Example:
    class MyWrapper
    {
        private Control control;

        public MyWrapper(Control control)
        {
            this.control = control;
        }

        public Control Control
        {
            get { return
    control; }
        }
    }

    2) Create a MouseDown event to start your dragging operation. Example:
    private void MyMouseDown(object sender, MouseEventArgs e)
    {
        Control source = (Control
    )sender;
        source.DoDragDrop(new MyWrapper(source), DragDropEffects
    .Move);
    }

    3) Assign the mouse event to all controls on your FlowLayoutPanel. Example:
    foreach (Control control in flowLayoutPanel1.Controls)
    {
        control.MouseDown += MyMouseDown;
    }
    If you add or remove controls at run-time, you can use the ControlAdded / ControlRemoved events of the FlowLayoutPanel to update your controls.

    4) Set the AllowDrop property of your FlowLayoutPanel to true.

    5) Create a DragEnter event for the FlowLayoutPanel. Example:
    private void flowLayoutPanel1_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(MyWrapper)))
            e.Effect = DragDropEffects.Move;
        else
            e.Effect = DragDropEffects.None;
    }

    6) Create a DragDrop event for the FlowLayoutPanel. Example:
    private void flowLayoutPanel1_DragDrop(object sender, DragEventArgs e)
    {
        MyWrapper wrapper = (MyWrapper)e.Data.GetData(typeof(MyWrapper
    ));
        Control
    source = wrapper.Control;

        Point mousePosition = flowLayoutPanel1.PointToClient(new Point
    (e.X, e.Y));
        Control
    destination = flowLayoutPanel1.GetChildAtPoint(mousePosition);

        int
    indexDestination = flowLayoutPanel1.Controls.IndexOf(destination);
        if (flowLayoutPanel1.Controls.IndexOf(source) < indexDestination)
            indexDestination--;

        flowLayoutPanel1.Controls.SetChildIndex(source, indexDestination);
    }

    Note: controls like Buttons, Labels, TextBoxes, etc. will behave nicely. Controls like RichTextBoxes require extra attention.

    Regards, Tonn


  • How to Move Controls at RunTime in a flowLayoutPanel Control?