Check List Box before Adding New Item

2019-09-06 00:34发布

问题:

I am trying to check that an item doesn't already exist in a list box before I add the new item.

            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";
        }

I have got it to check if the text box is blank, but I need to check that the item a user is trying to add is not already in the the list box.

I have tried the line:

if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null)

But that doesn't work, any suggestions on how I can do the check?

回答1:

think you should at least try to use TeamNameTextBox instead of TeamNameListBox as argument

if (TeamNameListBox.Items.FindByValue(TeamNameTextBox.Text) == null)


回答2:

Use this:

if (!TeamNameListBox.Items.Contains(TeamNameTextBox.Text))
                TeamNameListBox.Items.Add(TeamNameTextBox.Text);


回答3:

I suppose you mean

// search if the textbox value is found in the list. this comment shouldn't be part of the code
if (TeamNameListBox.Items.FindByValue(TeamNameTextBox.Text) == null) 

instead of

if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null) // code from question

EDIT: There is no need to put the name of the type of the control next to the variable.
i.e. instead of TeamNameListBox, use teamNames. And, instead of TeamNameTextBox, use teamName.