none
如何實現拖放(drag & drop) 在 tableLayoutPanel? RRS feed

所有回覆

  • HI,

     

    您可以將Label1的ColumnSpan屬性設定為2, 再將Label1往右拖即

     

    tihs

    2008年4月19日 上午 06:51
  •  

    剛剛試了一下 可以做到類似的效果

    首先先在Form_Load中, 將所有欄位的寬和高保存起來

    然後設定Label1的MouseDown事件, 開始拖曳, 並保存當時的座標

    拖曳到tableLayoutPanel1時分別處理DragEnter, DragOver, DragDrop

    並在DragDrop計算放掉後 要調整到哪一個格子就可以了

    如果你有需要跨欄位 只需要將Label1的ColumnSpan設定好就可以了(什麼樣的情況會有這個需求??)

    Code Snippet

            Point oldPoint = Point.Empty;
            int[] heights;
            int[] widths;
            private void Form1_Load(object sender, EventArgs e)
            {
                heights = tableLayoutPanel1.GetRowHeights();
                widths = tableLayoutPanel1.GetColumnWidths();
            }
            private void tableLayoutPanel1_DragEnter(object sender, DragEventArgs e)
            {
                if (e.Data.GetDataPresent(typeof(System.Windows.Forms.Label)))
                    e.Effect = DragDropEffects.All;
            }
            private void tableLayoutPanel1_DragOver(object sender, DragEventArgs e)
            {
                Label l = e.Data.GetData(typeof(System.Windows.Forms.Label)) as Label;
                l.Location = this.PointToClient(new Point(e.X - oldPoint.X, e.Y - oldPoint.Y));
                l.BringToFront();
            }
            private void tableLayoutPanel1_DragDrop(object sender, DragEventArgs e)
            {
                Point newPoint = this.PointToClient(new Point(e.X - oldPoint.X, e.Y - oldPoint.Y));
                int c = GetRowOrColume(newPoint.X, widths);
                int r = GetRowOrColume(newPoint.Y, heights);
                System.Diagnostics.Debug.WriteLine("r=" + r + "/" + "c=" + c);
                Label l = e.Data.GetData(typeof(System.Windows.Forms.Label)) as Label;
                tableLayoutPanel1.SetRow(l, r);
                tableLayoutPanel1.SetColumn(l, c);
                tableLayoutPanel1.ResumeLayout();
            }
            private void label1_MouseDown(object sender, MouseEventArgs e)
            {
                tableLayoutPanel1.SuspendLayout();
                tableLayoutPanel1.AllowDrop = true;
                oldPoint = new Point(e.X, e.Y);
                ((Control)sender).DoDragDrop(sender, DragDropEffects.All);
            }
            private void label1_MouseUp(object sender, MouseEventArgs e)
            {
                tableLayoutPanel1.ResumeLayout();
            }
            int GetRowOrColume(int x, int[] arr)
            {
                int sum = 0;
                for (int i = 0; i < arr.Length; i++)
                {
                    if (x >= sum && x <= sum + arr[i])
                    {
                        return i;
                    }
                    sum += arr[i];
                }
                return 0;
            }

     

     

    2008年4月21日 下午 11:30