这是我的代码:
public Form1()
{
InitializeComponent();
pBox1.AllowDrop = true;
}
private void pBox1_DragDrop(object sender, DragEventArgs e)
{
var bmp = (Bitmap)e.Data.GetData(DataFormats.Bitmap);
pBox1.Image = bmp;
pBox1.Size = new Size(100, 100);
}
private void pBox2_MouseDown(object sender, MouseEventArgs e)
{
if (DoDragDrop(pBox2.Image, DragDropEffects.Move) == DragDropEffects.Move)
{
pBox2.Image = null;
}
}
pBox1是我想要拖入的pictureBox,而pBox2是我想要拖动的pictureBox。我得到的错误是一个对象引用,没有设置为对象错误的实例,在行#34; if(DoDragDrop ...."在MouseDown方法中。
答案 0 :(得分:2)
如果您列出的是整个代码清单,则永远不会将pBox2.Image设置为Image,这会导致异常。可能想添加:
private void pBox2_MouseDown(object sender, MouseEventArgs e)
{
if(pBox2.Image != null)
{
if (DoDragDrop(pBox2.Image, DragDropEffects.Move) == DragDropEffects.Move)
{
pBox2.Image = null;
}
}
}
将pBox2初始化为某种图像......
public Form1()
{
InitializeComponent();
pBox1.AllowDrop = true;
pBox2.Image = Image.FromFile(@"YourFilePath");
}
<强> 修改 强> 只需注意,这可以消除您的异常,但仍然无法正确实现拖放。我正在玩它,如果找到合适的解决方案,我会和你一起回来。
<强> 修改 强>
可能与以下链接重复:
我使用以下方法开始工作:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.AllowDrop = true;
pictureBox1.AllowDrop = true;
pictureBox2.AllowDrop = true;
pictureBox2.Image = Image.FromFile(@"C:\TitleBar.jpg");
}
private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
{
if (pictureBox2.Image != null)
{
pictureBox2.DoDragDrop(pictureBox2.Image, DragDropEffects.Move);
pictureBox2.Image = null;
}
}
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
pictureBox1.Image = (Image)e.Data.GetData(DataFormats.Bitmap);
}
}