RadioButtons and Lambda Expressions
Posted
by MightyZot
on Geeks with Blogs
See other posts from Geeks with Blogs
or by MightyZot
Published on Wed, 28 Nov 2012 15:31:34 GMT
Indexed on
2012/11/28
17:06 UTC
Read the original article
Hit count: 233
Radio buttons operate in groups. They are used to present mutually exclusive lists of options. Since I started programming in Windows 20 years ago, I have always been frustrated about how they are implemented.
To make them operate as a group, you put your radio buttons in a group box. Conversely, to group radio buttons in HTML, you simply give them all the same name. Radio buttons with the same name or ID in HTML operate as one mutually exclusive group of options. In C#, all your radio buttons must have unique names and you use group boxes to group them.
I’m in the process of converting some old code to C# and I’m tasked with creating a user control with groups of radio buttons on it. I started out writing the traditional switch…case statements to check the appropriate radio button based upon value, loops to uncheck them all, etc. Then it occurred to me that I could stick the radio buttons in a Dictionary or List and use Lambda expressions to make my code a lot more maintainable. So, here is what I ended up with:
Here is a dictionary that contains my list of radio buttons and their values. I used their values as the keys, so that I can select them by value. Now, instead of using loops and switch…case statements to control the radio buttons, I use the lambda syntax and extension methods.
Selecting a Radio Button by Value
This code is inside of a property accessor, so “value” represents the value passed into the property accessor. The “First” extension method uses the delegate represented by the lambda expression to select the radio button (actually KeyValuePair) that represents the passed in value. Finally, the resulting checkbox is checked.
Since the radio buttons are in the same group, they function as a group, the appropriate radio button is selected while the others are unselected.
Reading the Value
This is the get accessor for the property that returns the value of the checked radio button.
Now, if you’re using binding, this code is likely not necessary; however, I didn’t want to use binding in this case, so I think this is a good alternative to the traditional loops and switch…case statements.
© Geeks with Blogs or respective owner