我想在添加新项目之前检查列表框中是否已存在某个项目。
if (TeamNameTextBox.Text != "")
{
if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null)
{
TeamNameListBox.Items.Add(TeamNameTextBox.Text);
TeamNameTextBox.Text = "";
int teamCountUpdate = TeamNameListBox.Items.Count;
if (teamCountUpdate == 1)
{
TeamCount.Text = teamCountUpdate.ToString() + " Team";
}
else
{
TeamCount.Text = teamCountUpdate.ToString() + " Teams";
}
}
else
{
AddTeamSeasonError.Text = "This team has already been added";
}
}
else
{
AddTeamSeasonError.Text = "Please select a team";
}
我已经检查文本框是否为空白,但是我需要检查用户尝试添加的项目是否已经在列表框中。
我试过这行:
if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null)
但这不起作用,关于如何进行检查的任何建议?
答案 0 :(得分:2)
if (!string.IsNullOrEmpty(TeamNameTextBox.Text))
{
if (!TeamNameListBox.Items.Contains(TeamNameTextBox.Text))
{
TeamNameListBox.Items.Add(TeamNameTextBox.Text);
}
else
{
// item already exists in listbox
}
}
else
{
// textbox is empty
}