我有一个小表单,用户在其中写入某个项目的名称,然后当他单击"添加"时,有一个语句需要检查checkedListBox中是否已存在相同的项目.
我正在寻找检查列表是空的还是某个项目的"if"语句.
private void button2_Click(object sender, EventArgs e)
{
foreach (var item in checkedListBox1.Items)
{
if (itemName.Text == item.ToString())
{
DialogResult result = MessageBox.Show("?", "Question", MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Yes)
{
checkedListBox1.Items.Add(itemName.Text);
}
else if (result == DialogResult.No)
{
//clear the forms
}
}
else
{
checkedListBox1.Items.Add(itemName.Text);
timeLeft = 2;
timer1.Start();
}
}
}
//checkedListBox1.Items.Add(itemName.Text);
//timeLeft = 2;
//timer1.Start();
Run Code Online (Sandbox Code Playgroud)
if(checkedListBox1.Items.Count > 0) {
// It contains items
} else {
// It doesn't
}
Run Code Online (Sandbox Code Playgroud)
编辑:用于检查CheckedListBox是否为空,然后
if(checkedListBox1.Items.Contains(theItemToCheck)) {
// The item is already in the CheckedListBox
}
Run Code Online (Sandbox Code Playgroud)
是检查项目是否已经在CheckedListBox中.