匹配列A按钮与列B面板c#

时间:2017-12-22 13:41:29

标签: c# button match panel

我已经制作了拖放程序,我将按钮移动到面板中,如下图所示,但我不知道如何验证panel1是否包含button1,因为我想制作一个程序匹配从A列到B列的项目(匹配按钮x到面板x并验证所有匹配是否正确:panel1中的button1,panel2中的button2 ......)。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace proiect_istorie
{
    public partial class DragAndDrop : Form
    {
        public DragAndDrop()
        {
            InitializeComponent();
        }

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

        private void panel_DragDrop(object sender, DragEventArgs e)
        {
            Button bt = ((Button)e.Data.GetData(typeof(Button)));
            bt.Parent = (Panel)sender;
            bt.Dock = DockStyle.Fill;
            bt.BringToFront();
        }

        private void button_MouseDown(object sender, MouseEventArgs e)
        {
            Button bt = (sender as Button);
            bt.DoDragDrop(sender, DragDropEffects.Move);
        }
    }
}

并且我已将每个按钮和面板与图片中的事件相关联,并且我不知道如何验证匹配是否在面板1中的按钮1 ...

event on panel

event on button

1 个答案:

答案 0 :(得分:1)

如果您将按钮的Tag属性和Panel设置为相同的字符串,则可以使用以下代码验证它们上的面板和按钮是否匹配:

private void check_Click(object sender, EventArgs e)
{
    textbox.Text = "";

    // loop over all controls of the Form
    foreach(var ctl in Controls)
    {
        var pnl = ctl as Panel;
        if (pnl != null)
        {
            // loop over the Controls in a Panel
            foreach(var pnlctl in pnl.Controls)
            {
                // find any buttons
                var bt = pnlctl as Button;
                if (bt != null)
                {
                    // check if the Tag property of the Panel matches that of the Button
                    textbox.AppendText( pnl.Name + " = " + ((bt.Tag ==  pnl.Tag)?"OK": "Not OK") + "\r\n");                
                }
            }
        }
   }
}

这就是它的实际行动:

drag and drop

当把一个按钮放在面板上没有或多个时,我把它留作练习来实现处理。