如何在不写一百万条if语句的情况下循环播放? 这是我错误的代码示例,因为它只会检查每个框,然后继续下一个框。忘了说所有十个复选框都在一个面板中,他们需要以任意组合进行检查。我不想写大量的&&或||我甚至无法计算组合请帮助我。
if (cbxTitle.Checked == true)
{
searched = "title";
}
else if (cbxAuthor.Checked == true)
{
searched = "author";
}
else if (cbxYear.Checked == true)
{
searched = "year";
}
else if (cbxWeight.Checked == true)
{
searched = "weight";
}
答案 0 :(得分:3)
您可以用以下内容替换if语句:
searched = this.Controls
.OfType<CheckBox>()
.First(x => x.Checked).Name.Substring(3).ToLower();
这假设有三件事:
CheckBox
Form
的直接子元素,它们不在Panel或其他容器中searched
的值。另外,请不要忘记将System.Linq
命名空间包含在using指令中,以便使用LINQ
方法(OfType
和First
)
答案 1 :(得分:1)
您必须订阅每个复选框的CheckedChange事件。
选中复选框后,请执行搜索操作。
答案 2 :(得分:0)
似乎您想要包含用户选择的所有搜索条件。如果你没有,那我肯定会使用单选按钮。
为了避免无休止的if
/ else
语句,我会在所有foreach
控件上使用CheckBox
循环,并且 - 假设您在变量名称 - 然后您可以使用名称的子字符串附加到搜索条件。
所以你的算法会或多或少:
Checkbox
Checked
,则提取其名称修改强>
根据您的要求,我正在添加样本。
由于它是一个搜索应用程序,我认为你会有一个“搜索选项”表单。
这是初始化此表单的部分。
namespace SearchApplication
{
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
public partial class SearchOptionsForm : Form
{
// prefix you used for all your checkboxes
private const string prefix = @"cbx";
// store *all* checkboxes in your form
// if you had other checkboxes in your form,
// you would need to think how you would want to differentiate them
private IEnumerable<CheckBox> searchOptionControls;
// represents all choices made by the user to customize the search type
private string searched;
// since your 'searched' variable is a string,
// you need a filter separator to be able to tell user selections apart
private const string optionSeparator = @";";
public SearchOptionsForm()
{
this.InitializeComponent();
// initialize your collection of checkboxes
this.searchOptionControls = this.Controls.OfType<CheckBox>();
}
}
}
这是在点击“Apply”
后对用户输入作出反应的代码namespace SearchApplication
{
using System;
using System.Windows.Forms;
public partial class SearchOptionsForm : Form
{
/// <summary>
/// Updates the 'searched' string with the selections made by the user.
/// </summary>
/// <param name="sender">The 'Apply' button.</param>
/// <param name="e">Not used in this implementation.</param>
private void ApplyClicked(object sender, EventArgs e)
{
// reset your filter after every click
this.searched = string.Empty;
// inspect all controls of interest
foreach (var currentOption in this.searchOptionControls)
{
// determine if user wants to use this filter
if (currentOption.Checked)
{
// append to your existing search options
searched += currentOption.Name.Substring(prefix.Length);
// include the filter separator
searched += optionSeparator;
}
}
// note that filter order in the string doesn't match display order
this.textBoxSearchFilters.Text = searched;
}
}
}