Frage

I am making a drapandrop and it's working nice. But I want it to give a message whenever I try to drag an image into a picture that already contains one, that won't work... When I click on an image and drag it to the same picturebox where it came from (like I click on picturebox1 and drop it on picturebox1 it just gets blank), it just disappears.public partial class Form1 : Form

    public Form1()
    {
        InitializeComponent();

        pictureBox1.AllowDrop = true;
        pictureBox2.AllowDrop = true;
        pictureBox3.AllowDrop = true;
        pictureBox4.AllowDrop = true;
        pictureBox5.AllowDrop = true;
        pictureBox6.AllowDrop = true;
    }

    void pictureBox_MouseDown(object sender, MouseEventArgs e)
    {
        DoDragDrop(sender, DragDropEffects.Move);

    }

    void pictureBox_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }

    void pictureBox_DragDrop(object sender, DragEventArgs e)
    {
        PictureBox pb = e.Data.GetData(typeof(PictureBox)) as PictureBox;

        if (pb.Image != null) 
        {
            ((PictureBox)sender).Image = pb.Image;
            pb.Image = null;           

        }
        else
        {                
            MessageBox.Show("The picturebox already contains an image.");
        }
     }
}

}

War es hilfreich?

Lösung

pb is a reference to the PictureBox that is being dragged. since you are droping on the same PictureBox you are dragging, pb and senrder are both referencing the same PictureBox, so the pb.Image = null; code line is clearing the image in the PictureBox. you need to add to your condition a check that pb is different then sender, like this: if (pb.Image != null && !pb.Equals(sender))

edit

Basically, You should use the DragEnter Event for that. If the PictureBox already contains an Image, you can set the e.Effect to DragDropEffects.None. that will also provide a better solition to the problem you described in the first place.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top