Thursday, July 28, 2016

Attach single event to a control array at run time

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

0 comments:

Post a Comment