Search This Blog

Thursday, July 30, 2009

Drag and Drop Picturebox on FlowLayoutPanel

Here is code example of re-order picture boxes within a FlowLayoutPanel at runtime.

// add FlowLayoutPanel on a Winform - named flowLayoutPanel1
public partial class TestForm: Form
{
       public TestForm()
        {
            InitializeComponent();
            this.flowLayoutPanel1.AllowDrop = true
        }
        private void AddImageToBlog(System.Drawing.Image image)
        {
            PictureBox pbox = new PictureBox();
            pbox.SizeMode = PictureBoxSizeMode.Zoom;            
            pbox.Height = (_picturebox_height * _ScaleFactor);
            pbox.Width = (_picturebox_width * _ScaleFactor);
            pbox.Visible = true;
            pbox.Image = image;

            pbox.MouseDown += new MouseEventHandler(pbox_MouseDown);
            pbox.DragOver += new DragEventHandler(pbox_DragOver);            
            pbox.AllowDrop = true;
            flpNewBlog.Controls.Add(pbox);
        }
       void pbox_DragOver(object sender, DragEventArgs e)
        {
            base.OnDragOver(e);
            // is another dragable
            if (e.Data.GetData(typeof(PictureBox)) != null)
            {
                FlowLayoutPanel p = (FlowLayoutPanel)(sender as PictureBox).Parent;                 
                //Current Position             
                int myIndex = p.Controls.GetChildIndex((sender as PictureBox));

                //Dragged to control to location of next picturebox
                PictureBox q = (PictureBox) e.Data.GetData(typeof(PictureBox));                
                p.Controls.SetChildIndex(q, myIndex);
            }           
        }
        void pbox_MouseDown(object sender, MouseEventArgs e)
        {
            base.OnMouseDown(e);
            DoDragDrop(sender, DragDropEffects.All);
        }
         void pbox_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }


}

No comments: