65278

Is there a simpler way to process check boxes?

In vb.net, I have a form that has a set of four Check Boxes. Each Check Box signifies that (when checked) the user wants to add a special instruction to their order. The code looks like this:

If SpecialInstruction1CheckBox.Checked Then AddSpecialInstruction(SPECIAL_INSTRUCTION_1_String) End If If SpecialInstruction2CheckBox.Checked Then AddSpecialInstruction(SPECIAL_INSTRUCTION_2_String) End If If SpecialInstruction3CheckBox.Checked Then AddSpecialInstruction(SPECIAL_INSTRUCTION_3_String) End If If SpecialInstruction4CheckBox.Checked Then AddSpecialInstruction(SPECIAL_INSTRUCTION_4_String) End If

I have a feeling that this code is unnecessarily verbose, feels repetitive, and could be simplified. How would I go about doing this, or is this not as "wrong" as it feels?

Answer1:

The first problem is that your special instructions should not be stored in separate variables. They should be stored in an array or some other kind of list. Then you could access them by index (e.g. specialInstructions(1)).

Then you can loop through the check boxes by index like this:

For i As Integer = 1 to 4 Dim box As CheckBox = DirectCast(Me.Controls("SpecialInstruction" & i.ToString() & "CheckBox"), CheckBox) If box.Checked Then list.Add(specialInstructions(i)) Next

Alternatively, you could store references to your check boxes in an array and then loop through them more easily, for instance:

Dim checkBoxes() As CheckBox = { SpecialInstruction1CheckBox, SpecialInstruction2CheckBox, SpecialInstruction3CheckBox, SpecialInstruction4CheckBox} ' ... For i As Integer = 0 to checkBoxes.Length - 1 If checkBoxes(i).Checked Then list.Add(specialInstructions(i)) Next

Another option would be to store the special instructions in the Tag property of each check box, then you could just retrieve the value from the control, like this:

For Each i As CheckBox In checkBoxes If i.Checked Then list.Add(i.Tag) Next

But that only makes sense if you don't need to reuse those special instructions values elsewhere in your code.

Answer2:

Actually the code isn't that bad in itself. It mainly depends on what AddSpecialInstruction does, exactly. Depending on your specifics it might be better to pass it a list of string instructions instead:

Dim list As New List(Of String) If SpecialInstruction1CheckBox.Checked Then list.Add(SPECIAL_INSTRUCTION_1_String) If SpecialInstruction2CheckBox.Checked Then list.Add(SPECIAL_INSTRUCTION_2_String) If SpecialInstruction3CheckBox.Checked Then list.Add(SPECIAL_INSTRUCTION_3_String) If SpecialInstruction4CheckBox.Checked Then list.Add(SPECIAL_INSTRUCTION_4_String) AddSpecialInstructions(list)

Since you also required code shrinking, I made If statements holding on one line. Shorter variable names would help on that too.

Recommend

  • R: Plotly and subplot(): fastest way to create a subplot based on a factor
  • Non-recursive algorithm for full permutation with repetitive elements?
  • Error in package.json deploying Angular2 project on Azure using bitbucket
  • Node-SQLite's db.each using large amount of memory for broad queries
  • Send database data through socket connection
  • How to create CRITICAL events for Windows Event Viewer?
  • Using BOOST_FOREACH with a constant intrusive list
  • Parent element is ready before its child - Polymer 1.0
  • Removing multiple recurring text from pandas rows`
  • flatten multidimensional array into csv text with PHP
  • R Data table setkey - error some columns are not in the data.table
  • Converting DatetimeIndex to Timedelta index
  • asterisk agi (php) file debugging
  • Unwrap optionals in for statement
  • Why nullable types will not be equal in this case?
  • Specify datetime format for WCF Data Service
  • How can I export a gbm model in R?
  • How can I cons a list of pairs on to auto-mode-alist?
  • Controlling volume of running applications in Mac OS X via Objective-C
  • Why do empty folders disappear when adding Visual Studio solution to TFS?
  • C++ alternatives to preprocessor macro code generation?
  • Entity Framework Core 2.0 add-migration not generating anything
  • how to migrate existing records to match new ORM in rails
  • dropzone.js form submit not sending file
  • How to parse Java properties which contains variables?
  • Avoiding dependencies is exploding the number of projects in my VS solution
  • mysql select inside limit
  • Return to second to last URL in MVC (return View with previous filter conditions applied)?
  • How to create a new Bundle object?
  • custom UITableViewCell with image for highlighting
  • ActiveRecord query for a count of new users by day
  • Meteor: Do Something On Email Verification Confirmation
  • Running a C# exe file
  • Join two tables and save into third-sql
  • Where to put my custom functions in Wordpress?
  • How to model a transition system with SPIN
  • ORA-29908: missing primary invocation for ancillary operator
  • RestKit - RKRequestDelegate does not exist
  • WPF Applying a trigger on binding failure
  • Converting MP3 duration time