【问题标题】:Check List Box before Adding New Item添加新项目前检查列表框
【发布时间】:2013-03-21 03:22:22
【问题描述】:

在添加新项目之前,我正在尝试检查列表框中是否存在项目。

            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)

但这不起作用,关于如何进行检查有什么建议吗?

【问题讨论】:

  • 请不要多次发布同一个问题。我投票结束你问的另一个问题。谢谢。

标签: c# asp.net listbox


【解决方案1】:

使用这个:

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

【讨论】:

    【解决方案2】:

    认为您至少应该尝试使用 TeamNameTextBox 而不是 TeamNameListBox 作为参数

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

    【讨论】:

      【解决方案3】:

      我想你是说

      // 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) 
      

      而不是

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

      编辑:无需将控件类型的名称放在变量旁边。
      即,使用 teamNames 代替 TeamNameListBox。并且,不要使用TeamNameTextBox,而是使用teamName

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多