【问题标题】:object not set to instance of an object!! ComboBox SelectedIndex SelectedItem对象未设置为对象的实例!!组合框 SelectedIndex SelectedItem
【发布时间】:2010-10-06 10:12:47
【问题描述】:

我正在开发一个程序,它获取所有 Clearcase 区域(基本上是字符串)并将它们添加到组合框。我比较了组合框中新添加的项目中现有的明文区域字符串,如果找到,那么我想选择它,但是因为第一次没有选择任何内容,所以 selectedItem 为 null & selectedIndex = -1。 当我将 0 分配给 selectedIndex 时,错误来了 --> 对象未设置为对象的实例!!将某些内容分配给 selectedItem 时出现同样的问题;报错。

我的代码有什么问题?

    private void PopulateClearCaseRegionComboBox ( )
    {
        clearCaseRegionComboBox.Items.Clear();

        foreach ( Match token in RegularExpression.Match( "\\w+", clearTool.CmdExec( "lsregion" ) ) )
        {
            clearCaseRegionComboBox.Items.Add(token.Value.Trim());
            if (clearCaseRegion.ToUpperInvariant() == token.Value.Trim().ToUpperInvariant())
            {
                clearCaseRegionComboBox.SelectedIndex = clearCaseRegionComboBox.Items.IndexOf(token.Value.Trim());
            }
        }
        clearCaseRegionComboBox.Sorted = true;
    }

【问题讨论】:

    标签: combobox clearcase selecteditem selectedindex


    【解决方案1】:

    您确定以下行返回有效索引吗?

    clearCaseRegionComboBox.Items.IndexOf(token.Value.Trim());

    【讨论】:

      【解决方案2】:

      Add 方法返回新添加项的索引。您可以在 if 语句中使用该值。

      private void PopulateClearCaseRegionComboBox ( )
      {
          clearCaseRegionComboBox.Items.Clear();
      
          foreach ( Match token in RegularExpression.Match( "\\w+", clearTool.CmdExec( "lsregion" ) ) )
          {
              int index = clearCaseRegionComboBox.Items.Add(token.Value.Trim());
              if (clearCaseRegion.ToUpperInvariant() == token.Value.Trim().ToUpperInvariant())
              {
                  clearCaseRegionComboBox.SelectedIndex = index;
              }
          }
          clearCaseRegionComboBox.Sorted = true;
      }
      

      【讨论】:

        【解决方案3】:

        也许您可以在上下文中显示更多代码?我这样说是因为在您的代表性代码中此时似乎不可能出现此错误。您已经使用该对象添加了第 3 行的项目。

        您是否沉迷于组合框上将 clearCaseRegionComboBox 变量分配为 null 的任何事件?

        【讨论】:

          【解决方案4】:

          通知:当您设置 SelectedIndex 或 SelectedItem 时,也会发生 SelectedIndexChanged 事件。因此,如果您在那里有东西,也请检查一下。 :) 我已经过了几个小时,因为你在调试时看不到它。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-02-19
            • 2011-12-17
            • 2018-09-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多