是否有更简单的方法来处理复选框

是否有更简单的方法来处理复选框

本文介绍了是否有更简单的方法来处理复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在vb.net中,我有一个包含四个复选框的表单。每个复选框表示(检查时)用户想要在其订单中添加特殊指令。代码如下所示:

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?

推荐答案

第一个问题是您的特殊说明不应存储在单独的变量中。它们应存储在数组或其他类型的列表中。然后你可以通过索引访问它们(例如 specialInstructions(1))。

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.

这篇关于是否有更简单的方法来处理复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:27