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

Match column A button with column B panel c#

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

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

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

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");                
                }
            }
        }
   }
}

实际效果如下:

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