Solved

Index out of range for listBox.selectedIndex

Posted on 2003-11-27
7
1,088 Views
Last Modified: 2008-02-26
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
0
Comment
Question by:WhatupE
7 Comments
 
LVL 20

Expert Comment

by:TheAvenger
ID: 9836240
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
 

Author Comment

by:WhatupE
ID: 9837533
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
 
LVL 20

Expert Comment

by:TheAvenger
ID: 9837594
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:WhatupE
ID: 9837727
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
 
LVL 20

Accepted Solution

by:
TheAvenger earned 100 total points
ID: 9837738
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
 
LVL 27

Expert Comment

by:Dabas
ID: 9840445
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
 
LVL 10

Expert Comment

by:Duy Pham
ID: 9845221
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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This is a video describing the growing solar energy use in Utah. This is a topic that greatly interests me and so I decided to produce a video about it.

943 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now