简体   繁体   中英

C# Many Buttons

The question has arisen.

Suppose, there is a form on it 10 buttons. Is there any possibility to combine these buttons in a single "structure"(union of buttons)? To be able to work with them in style ...

ManyButtons.click += new System.EventHandler(this.button_Click);

I need to catch only the Events , without properties and methods

And most importantly, without arrays.

Personally, I would just tackle it by adding the Button s to a List and doing a foreach over that list.

That is, unless there is a particular reason to do otherwise?

It's all about that.

I used foreach without List in style

foreach (var c in this.Controls)
        {
            if (c is Button)
                ((Button)c).Click += new System.EventHandler(this.Buttons_Click);
        }

This will help avoid a mad number of rows processing event. And when I click on Button, my analizer checks this click and acts.

The question has arisen.

Ummm.... ok!

Create your own container which abstracts it, exposes the events you're interested in and behind the scenes manages the list of buttons for you. Then you'll have a simple interface in which to talk to instead of a stack of buttons.

You can handle all buttons clicks in the single event handler:

ManyButton1.click += new System.EventHandler(this.button_Click);
ManyButton2.click += new System.EventHandler(this.button_Click);
...

Inside event handler, sender parameter allows to detect, which button was clicked. You can use Tag property as button ID.

If you want to create event handler for some buttons, select them all (by holding Ctrl key), then go to properties box and create that event handler. This is the easiest and most convenient way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM