首页 > 解决方案 > 如何使返回 true 的多个 if 条件在 C# 中执行?

问题描述

我有一个checkedListBox,用户可以在其中选择他们想要更新的任何内容。我希望他们能够自由地更新一台机器的 1 到 5 个特性。因此,当他们只想更新 1 个事物时,他们不必提供其他 4 个特征。此外,当他们想要更新 5 个特性时,他们可以一口气完成。为此,我有以下 if 语句:


if (clbCharacteristicsToUpdate.CheckedItems.Count != 0)
{
                        if (clbCharacteristicsToUpdate.GetSelected(0))
                        {
                            currentITime = Convert.ToDouble(tbCurrentITime.Text);
                            MessageBox.Show(currentITime.ToString());
                            dh.UpdateCurrentITime(machineNr, currentITime);
                        }
                        if (clbCharacteristicsToUpdate.GetSelected(1))
                        {
                            cycleTime = Convert.ToDouble(tbCycleTime.Text);
                            MessageBox.Show(cycleTime.ToString());
                            dh.UpdateCycleTime(machineNr, cycleTime);
                        }
                        if (clbCharacteristicsToUpdate.GetSelected(2))
                        {
                            nrOfLinesPerCm = Convert.ToInt32(tbNrOfLinesPerCm.Text);
                            MessageBox.Show(nrOfLinesPerCm.ToString());
                            dh.UpdateNrOfLinesPerCm(machineNr, nrOfLinesPerCm);
                        }
                        if (clbCharacteristicsToUpdate.GetSelected(3))
                        {
                            heightOfLamallae = Convert.ToDouble(tbHeightOfLamallae.Text);
                            MessageBox.Show(heightOfLamallae.ToString());
                            dh.UpdateHeightOfLamallae(machineNr, heightOfLamallae);
                        }
                        if (clbCharacteristicsToUpdate.GetSelected(4))
                        {
                            if (rbLTB.Checked)
                            {
                                machineType = 2;
                                MessageBox.Show(machineType.ToString());
                            }
                            else if (rbSTB.Checked)
                            {
                                machineType = 1;
                                MessageBox.Show(machineType.ToString());
                            }
                            if(!rbLTB.Checked && !rbSTB.Checked)
                            {
                                MessageBox.Show("Select a machine type to update!");
                                return;
                            }
                            dh.UpdateType(machineNr, machineType);  
                         }

}

我的问题是,当我选择并更新 1 件事时,它可以完美运行。但是当我选择多个时,它只执行最后一个返回 true 的 if 语句。我考虑过使用 if-else 但只有第一个返回 true 的会被执行。我还考虑过为每种可能性设置 if 语句。但由于我有 5 个可以更新的特征,这将产生 25 种可能性,我不想有 25 个 if 语句。提前致谢!

标签: c#if-statementcheckedlistbox

解决方案


GetSelected不检查该项目是否已被检查,但它实际上已被选中。
例如,在下图中,“项目 2”将为GetSelected. 它被选中,而不是选中

选中列表框

相反,您可以执行检查clbCharacteristicsToUpdate.CheckedItems属性以获取实际检查的项目之类的操作。

GetSelected方法实际上来自于继承ListBox自的类CheckedListBox


推荐阅读