Hi.. right now i'm doing hangman project, and i have some problem to deal with. As you know, hangman game consist of many letters button (A,B,C,D,....Z), and usually when the user click a button, it became disable. I already know how to disable it, which is

private void btnQ_Click(object sender, EventArgs e)
        {
            btnQ.Enabled = false;
        }

It's only for one button (Button Q). I can add similar event for the other button, but i think it's waste of coding line.

Is there another way to solve this ? e.g. Define one event for all button click based on button's name.

I have tried this, but it didn't work at all.

string m_CurrButton = "";

public frmMain()
        {
            InitializeComponent();

            m_CurrButton = "btnQ";
            this.FindControlRecursive(panel2, m_CurrButton).Click += new EventHandler(frmMain_Click);

            m_CurrButton = "btnW";
            this.FindControlRecursive(panel2, m_CurrButton).Click += new EventHandler(frmMain_Click);
        }

 void frmMain_Click(object sender, EventArgs e)
        {
            this.FindControlRecursive(panel2, m_CurrButton).BackColor = Color.Red;
            this.FindControlRecursive(panel2, m_CurrButton).Enabled = false;
        }

   public Control FindControlRecursive(Control container, string name)
        {
            if (container.Name == name)
                return container;

            foreach (Control ctrl in container.Controls)
            {
                Control foundCtrl = FindControlRecursive(ctrl, name);
                if (foundCtrl != null)
                    return foundCtrl;
            }
            return null;
        }

Thanks before and after

Use something like this in your Click event handler :

Button theBtn = sender as Button;
theBtn.Enabled = false;

and in design mode assign the same Click handler to all your buttons.

Wow... It works well for me. Thanks a lot dude. I'm very appreciate it. GBU

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.