Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Index out of range for listBox.selectedIndex

Posted on 2003-11-27
7
Medium Priority
?
1,265 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 400 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

705 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