C# Add Action To All Buttons

How To Add Action To All Buttons In The Form Using C#

add action to all buttons in c#



This C# tutorial will provide a guide on creating a click event and applying it to all buttons within a form in CSharp programming language, utilizing the Visual Studio IDE. By following the steps outlined in this tutorial, you will gain valuable insight into effectively managing event handling in your C# projects.




Project Source Code:

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 WindowsFormsApplication1
{
    public partial class AddEventToAllButtons : Form
    {
        public AddEventToAllButtons()
        {
            InitializeComponent();
        }

        private void AddEventToAllButtons_Load(object sender, EventArgs e)
        {

            foreach (Control c in Controls)
            {
                if (c is Button)
                {
                    c.Click += new System.EventHandler(btn_Click);
                }
            }

        }

        private void btn_Click(object sender, EventArgs e)
        {
            Button btn = (Button) sender;
            label1.Text = btn.Text;

        }
        
    }
}                                       

////// OUTPUT : 

add event click to all buttons using c#





Share this

Related Posts

Previous
Next Post »