Index out of range for listBox.selectedIndex

I have a table called Runs with columns RunID and RunName.  I have a comboBox (comboBox1) and an arrayList (al2).  The comboBox already has 3 items.  I add two items to the comboBox (and the arrayList) in another function.  Then I delete the two added items.  When I delete the first added one (fourth overall), everything is fine.  But when I delete the second added one (last in the list), I get the error message:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range.  Must be non-negative and less than the size of the collection.

The message points to the arrowed line, however I beleive the error is occuring in the line before it.

private void LoadRuns(){
   string strQry="Select RunID, RunName from Runs Order By RunID";

   comboBox1.DataSource = null;
                  
   al2.RemoveRange(0, al2.Count);

   myConnection.Open();

   System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand(strQry, myConnection);

   System.Data.OleDb.OleDbDataReader myReader = myCommand.ExecuteReader();
                  
   while(myReader.Read())
   {

      TestObj obj1 = new TestObj(Convert.ToInt16(myReader[0]), Convert.ToString(myReader[1]));
        //listBox1.Items.Add(myReader[0]);
      al2.Add(obj1);

   }
   myReader.Close();

   comboBox1.DataSource = al2;
   comboBox1.DisplayMember = "Value";
   //MessageBox.Show(comboBox1.Items.Count.ToString());
   comboBox1.SelectedIndex = 0;
   myConnection.Close(); <---------------
}

Any help is greatly appreciated
WhatupEAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

TheAvengerCommented:
Note that this is an often mistake in the Visual Studio - to see highlighted the line AFTER the error. I don't know if they fixed it in 2003...

What did the line:
MessageBox.Show(comboBox1.Items.Count.ToString());
show you? you could try to change the line with the selected index to:

if (comboBox1.Items.Count > 0)
  comboBox1.SelectedIndex = 0;

Then you will not have a crash but maybe you have another problem with the logic. Why is this method (which filles in the combo box) called when you remove an item?
0
WhatupEAuthor Commented:
They didn't fix the error...I am running 2003.  The message box always displayed the correct # of items, which was always positive, so the if statement you have will always be true.  The method is filled because instead of writing new code after i delete the item from the database, I just reload everything.  Meaning I rerun the query, reload the arrayList, and reset the comboBox's datasource.  Should I be doing something else?  The code that calls this function is here:

DeleteRun(){
      myConnection.Open();
                        
      string strDel="Delete from Runs Where RunName = '" +comboBox1.Text+ "'";

      System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand(strDel, myConnection);
      
                myCommand.ExecuteNonQuery();

                string strQry="Select RunID from Runs Where RunName ='" +comboBox1.Text+ "'";

                System.Data.OleDb.OleDbCommand myCommand2 = new System.Data.OleDb.OleDbCommand(strQry, myConnection);

      System.Data.OleDb.OleDbDataReader myReader = myCommand2.ExecuteReader();

                              
      if(myReader.HasRows)
      {
            myReader.Read();
      
            string strDel2 = "Delete From TestRun Where RunID =" +Convert.ToInt16(myReader[0]);
                                    
            System.Data.OleDb.OleDbCommand myCommand3 = new System.Data.OleDb.OleDbCommand(strDel2, myConnection);
      
            myCommand3.ExecuteNonQuery();
      }
      myReader.Close();            
                  
      myConnection.Close();
      LoadRuns();
}
0
TheAvengerCommented:
Why do yo make two delitions? Just asking.... You could do it with only the first one....

You could simplify (and also fasten) the application if you just make:

comboBox1.Items.Remove (comboBox1.SelectedItem);

This has no call to the database, so it should be faster.

Otherwise try changing this:

al2.RemoveRange(0, al2.Count); -> al2.Clear();

This is a problem, because the range is actually from 0 to al2.Count - 1!
Try it and post again
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

WhatupEAuthor Commented:
I tried that last nite after I posted...no effect.  I am doing deletions to two different tables...the second of which is not important to this question.  And I can't just remove the item because it is connected to an arrayList as it's dataSource, and your statement only deletes from the comboBox.  

However, I have found a solution this morning.  At the beginning of my LoadRuns() function, I set the selectedIndex to -1.  That's it.  

But thanks again for your help TheAvenger.
0
TheAvengerCommented:
If setting the index to -1 works, then the problem was that the current item si removed and it still tries to select it after reload. Maybe that's it, who knows... Call MS :-))
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DabasCommented:
Hi WhatupE:
>    comboBox1.SelectedIndex = 0;
>    myConnection.Close(); <---------------

Can only give you limited help here, since I am more a VB.NET person than a C# person

First of all, I would recomment you use try..catch.. end try (or the c# equivalent to it)

I have the feeling the error is not in LoadRuns but in comboBox1_SelectedIndexChanged
Are you handling that event?
When your code calls comboBox1.SelectedIndex = 0, it triggers that event, and might be causing your error.
Since you are not try catching there, .NET shows the error to be in the next statement.


Dabas
0
Duy PhamFreelance IT ConsultantCommented:
You should remove the item in combobox before deleting from object or database object that combobox binding to. And if reload automatically, you should check if after delete, binded object has no item then you clear the datasource property of combobox control. So i think the problem will be done.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.