检查阵列的多个复选框的状态

时间:2017-10-01 18:17:19

标签: c# winforms

我有一个数组,我需要根据多组复选框的状态过滤记录,然后检查我的数组,看它是否包含与选中的复选框匹配的相应值之一的值。我需要用大约10个不同的复选框组来完成这个...其中两个如下所示。另一个警告是,假设现在第一个显示了3个复选框,但如果客户想到更多标准,明年可能会有4个复选框。所以我想要一些东西让我在添加新复选框时不会更改代码。有没有更好的方法来做到这一点,或者我只需要按照下面的方式对每个复选框组进行检查?

var showRecord = false;

// 3 at this time...but could be more one day.
if (checkboxDevelopment.Checked && myArray[10].ToString() == "Development")
    || (checkboxStaging.Checked && myArray[10].ToString() == "Staging"
    || (checkboxProduction.Checked && myArray[10].ToString() == "Production")
{
    showRecord = true;
}
else
{
    showRecord = false;
}

// If the 1st test passed, keep checking.
if (showRecord)
{
    // 4 in this group...but could be more one day.
    if (checkboxPass.Checked && myArray[11].ToString() == "Pass")
        || (checkboxFail.Checked && myArray[11].ToString() == "Fail"
        || (checkboxUnknown.Checked && myArray[11].ToString() == "Unknown"
        || (checkboxError.Checked && myArray[11].ToString() == "Error")
    {
        showRecord = true;
    }
    else
    {
        showRecord = false;
    }

}

// A bunch more checkboxes to go through until I can decide if to show the record or not.
...

if (showRecord)
{
    // Code to show the record in the user's search results.
}

1 个答案:

答案 0 :(得分:0)

唯一想到的是: 如果您遵循代码段中的命名约定并将每组复选框放入其自己的组中,则可以尝试以下操作:

 var showRecord = false;
        foreach (CheckBox item in checkboxGroup1)
        {
            if (item.Checked && myArray[10].ToString()==item.Name.ToString().Substring(8))
            {
                showRecord = true;
                break;
            }
        }

所以你遍历复选框组,如果选中了任何复选框+名称是正确的,那么它会将showRecord设置为true并打破循环。 然后重复每组复选框。 希望这会有所帮助。