C#拖放 - Muliple图片框到面板或流程布局面板

时间:2015-10-09 06:31:52

标签: c# drag-and-drop

我目前正在实施阻力& C#Window Forms中的drop函数。我在左侧导航栏中创建了多个图片框,因此用户可以拖放到右侧面板。

但它确实看起来像图片框不能直接掉到面板上。 当我编译时,它会运行。但是,当我拖放它时会出现以下错误:

"unable to cast object of type 'System.Windows.Forms.Panel' to type 'System.Windows.Forms.PictureBox'."

请建议我如何拖放" picutre 1,2,3"相应的小组。?

    private void Form3_Load(object sender, EventArgs e)
    {
        pictureBox4.DragEnter += new DragEventHandler(pictureBox4_DragEnter);
        pictureBox4.DragDrop += new DragEventHandler(pictureBox4_DragDrop);
        pictureBox4.MouseDown += new MouseEventHandler(pictureBox4_MouseDown);

        panel2.AllowDrop = true;
    }

    private void pictureBox4_DragDrop(object sender, DragEventArgs e)
    {
        PictureBox pb = (PictureBox)sender;
        pb.Image = (Image)e.Data.GetData(DataFormats.Bitmap);
    }

    private void pictureBox4_MouseDown(object sender, MouseEventArgs e)
    {

        PictureBox pb = (PictureBox)sender;
        pb.Select();
        pb.DoDragDrop(pb.Image, DragDropEffects.Copy);
        panel1.Show();
    }

    private void panel2_DragDrop(object sender, DragEventArgs e)
    {
        PictureBox pb = (PictureBox)sender;
        pb.Image = (Image)e.Data.GetData(DataFormats.Bitmap);

    }

    private void panel2_DragEnter(object sender, DragEventArgs e)
    {

        if (e.Data.GetDataPresent(DataFormats.Bitmap))
        {
            e.Effect = DragDropEffects.Copy;

        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }

1 个答案:

答案 0 :(得分:0)

我认为在此代码中,您的发件人实际上是一名专家组。在调试器中检查它的类型:

private void panel2_DragDrop(object sender, DragEventArgs e)
{
    PictureBox pb = (PictureBox)sender;
    pb.Image = (Image)e.Data.GetData(DataFormats.Bitmap);

}

作为一个好的原则总是像这样进行类型转换:

PictureBox pb = sender as PictureBox; // will give you null if it can't be cast to PictureBox
if(pb != null)
{
    // do something...
}