检查面板是否包含某些内容

时间:2015-02-13 10:35:42

标签: c# drag-and-drop panel

private void PBoxJigsaw1_MouseUp(object sender, MouseEventArgs e)
    {
        if (sender != null && sender.GetType() == typeof(PictureBox))
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                PictureBox answer = (PictureBox)sender;

                if (answer.Location.X < pnlJigsaw5.Location.X && answer.Location.Y > pnlJigsaw5.Location.Y)
                {
                    if (answer.Location.X + answer.Width > pnlJigsaw5.Location.X)
                    {
                        if ((answer.Location.X + answer.Width) < pnlJigsaw5.Location.X + pnlJigsaw5.Width)
                        {
                            answer.Location = pnlJigsaw5.Location;
                        }
                    }
                }
                else if (answer.Location.X < pnlJigsaw1.Location.X && answer.Location.Y > pnlJigsaw1.Location.Y)
                {
                    if (answer.Location.X + answer.Width > pnlJigsaw1.Location.X)
                    {
                        if ((answer.Location.X + answer.Width) < pnlJigsaw1.Location.X + pnlJigsaw1.Width)
                        {
                            answer.Location = pnlJigsaw1.Location;
                        }
                    }
                }

我在c#上创建了一个拼图,用户将pictureBox拖动到面板中以创建图像。我想知道是否有可能检查一个面板是否包含某些东西,因为当时很多图片盒可以进入一个面板并且看起来它们会消失,尽管它们只是在彼此之后。我只是想让它一次只能在一个面板中只有一个pictureBox。感谢

1 个答案:

答案 0 :(得分:4)

您可以检查panel上的pictureBox是否包含任何controls

if(panel.Controls.Count > 0)
{
  // Panel contains items inside
  // Ignore Panel
}

EDIT1: 您是否尝试将此代码放在活动的顶部?喜欢这个

private void PBoxJigsaw1_MouseUp(object sender, MouseEventArgs e)
{
    if(panel.Controls.Count > 0) 
    {
        return; // Panel already contains a control, stop executing the code
    }

    if (sender != null && sender.GetType() == typeof(PictureBox))
    {
        ....

这是否会使图片框消失?