Donate

Attach Single Event To A Control Array At Run Time Using LINQ And C#

In a scenario wherein you need to attach a single event like CheckedChanged() to a control array such as CheckBox controls, the common way to do it is using for each or for loop. Another way to achieve it is using LINQ's ForEach() method as demonstrated below.
Event Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
void CheckBoxGeneric_CheckedChanged(object sender, EventArgs e)
{
 var checkBox = (CheckBox)sender;
 if (checkBox.Name == "chkBurger")
 {
  //...
 }
 else if (checkBox.Name == "chkSoda")
 {
  //...
 }
 else
 {
  //...
 }
}

Attach the event to the control array
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
private CheckBox[] OrderItems;
OrderItems = new CheckBox[] { chkBurger, chkSoda, chkIceCream };

private void Form1_Load(object sender, EventArgs e)
{
 //solution 1 using foreach loop
 //foreach (var checkControl in OrderItems)
 //{
 //    checkControl.CheckedChanged += new EventHandler(CheckBoxGeneric_CheckedChanged);
 //}

 //solution 2 using LINQ 
 OrderItems.ToList().ForEach(checkVal => checkVal.CheckedChanged 
   += new EventHandler(CheckBoxGeneric_CheckedChanged));
}

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations