views:

878

answers:

4

I am developing a program which gets all Clearcase regions (basically strings) & adds them to Combo box. I compare an existing clearcase region string in newly added items in combo box & if it is found then I want to select it, but because nothing is selected for the first time, selectedItem is null & selectedIndex = -1. when I assign 0 to selectedIndex, error comes --> object not set to instance of an object!! same problem when you assign something to selectedItem; gives an error.

whats wrong with my code?

 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;
 }
+1  A: 

Are you sure the following line returns a valid index?

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

SDX2000
A: 

The Add method returns the index of the newly added item. You can use that value inside your if statement.

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;
}
Scott Stevenson
A: 

Thanks. But problem is still there. I get "object reference not set to an instance of an object" error on line --> clearCaseRegionComboBox.SelectedIndex = index;

Please help.

A: 

Perhaps you can reveal more of your code in context? I say this because it would seem impossible to get this error at this point in your representative code. You've already used the object to add an item 3 lines up.

Are you sinked to any events on the combo box that would assign the clearCaseRegionComboBox variable to null?

Scott Stevenson