0

I've searched several questions like this but could not find a good answer to my problem.

I have 2 listboxes, one contains a list of check numbers and the other contains a list of payees. The code was working fine and I did some error checking enhancements to prevent user errors and now I am getting this message

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

In debug I see that the Payee list box has 41 items - which is correct, so when the selection changes on the Check list in this event I have to select that particular check payee. It is the second one in the Payee List and my index has a value of 1 and this error shows up.

I've been hitting my brains on this error for the last 2 hours... here is the "offending" code.

(Inside the event handler) ...

queryReadType.Connection = conn;
conn.Open();
queryReadType.Parameters.Add("@fld1", SqlDbType.VarChar, 50).Value = checkNo;
SqlDataReader reader = queryReadType.ExecuteReader();
try
{
    int i, zid;
    while (reader.Read())
    {
        int.TryParse(reader["id"].ToString(), out zid);
        txtCheckNo.Text = reader["checkno"].ToString();
        if (option == 60) // Update
          originalCheckNo = txtCheckNo.Text;  
        int payeeId;
        int.TryParse(reader["payeeid"].ToString(), out payeeId);
        txtPayeeId.Text = payeeId.ToString();
        string payee = reader["payee"].ToString();
        for (i = 0; i < payeecnt; i++)
        {
            if (String.Compare(payee, lstPayee.Items[i].ToString()) == 0)
            {
                 lstPayee.ClearSelected();
                 //int j = lstPayee.Items.Count;  <---- shows 41
                 lstPayee.SetSelected(i, true); <--- the value of i is 1 which //is the correct payee for this check
                  break;
            }
         }
         DateTime dtissued = DateTime.MinValue;
         //DateTime dtcleared = DateTime.MinValue;
         colIndex = reader.GetOrdinal("dateissued");
         if (!reader.IsDBNull(colIndex))
               dtissued = reader.GetDateTime(colIndex);

.....

I'd appreciate someone shedding some light on what could be wrong - and it was working perfectly - again this code in inside the selection item change for the check listbox, and please only positive comments I have enough baggage in my work day already... I've notice that some members post comments that don't really address the issue, if this has been answered already please post the link.

Thanks in advance

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • 1
    http://stackoverflow.com/questions/20940979/what-is-indexoutofrangeexception-and-how-do-i-fix-it – Soner Gönül Sep 05 '15 at 15:55
  • PS> The error message comes up but the proper "payee" is highlighted on the payees listbox – Paul Rosemberg Sep 05 '15 at 16:00
  • Where are you setting `payeecnt`? Try to replace it with `lstPayee.Items.Count`. Btw.: shouldn't you call `ClearSelected` before the while-loop. Otherwise only the last one we be selected. – Olivier Jacot-Descombes Sep 05 '15 at 16:08
  • `int.TryParse(reader["id"].ToString(), out zid);` Why are you using TryParse but ignoring the return value (true or false)? Also, it looks like you are storing integers as text. That can only cause problems. – Steve Wellens Sep 05 '15 at 16:10
  • If `id` is an int, use `reader.GetInt32(ordId)` instead and declare `int ordId = reader.GetOrdinal("id");` before the loop. – Olivier Jacot-Descombes Sep 05 '15 at 16:13
  • By the way, you can compare string equality in C# with `==`. – cbr Sep 05 '15 at 16:25

2 Answers2

0

My bet would be that payeecnt doesn't hold the correct value. I fail to see where it gets its value from. However, in your for block use the Items.Count value instead of payeecnt, like so:

for (i = 0; i < lstPayee.Items.Count; i++) 
{
   if (String.Compare(payee, lstPayee.Items[i].ToString()) == 0) 
   {
      lstPayee.ClearSelected(); //int j = lstPayee.Items.Count; <---- shows 41 
      lstPayee.SetSelected(i, true); <--- the value of i is 1 which //is the correct payee for this check 
      break;
   }
}
Mihai Caracostea
  • 8,336
  • 4
  • 27
  • 46
  • I had refactored the code and created a function to load my list boxes and somehow left out the filling of an internal array which I had created and somehow left out when consolidating the action. I'll try and answer some of the comments – Paul Rosemberg Sep 06 '15 at 18:23
  • payeenct is set at the load form event, if the user needs to "add" a new payee he/she exists this form and adds a payee then comes back to write a check to a new payee. The list box number of selected items is set to 1 at design time, the ClearSelected is not necessary in my code, I've added it there while trying to debug the error – Paul Rosemberg Sep 06 '15 at 18:24
  • In the database integers are stored as integers and textPayeeId is a hidden text field that is used by the action buttons to check if the data is correctly filled out before proceeding with db updates since it is a foreign key in the checks table. As for Olivier comment thanks. But can you explain to me how did you get the value of ordId? Which is the reason for my statement... – Paul Rosemberg Sep 06 '15 at 18:24
  • I was "blackballed" by stackoverflow for a day, 1 day timeout for not adhering to "correct" tag selection and not pursuing more checking of calls stack tracing. I did force me to re check what changes I had made and to find out that I had left out the filling of an array which is not called in this code but that evidently led to some memory leak and Visual Studio error. StackOverflow is a great source of answers when I am looking how to solve a problem but the sometimes condescending tone of some answers is very negative. Thank again for the members that tried and help – Paul Rosemberg Sep 06 '15 at 18:24
  • In the form load event I am calling LoadLists - snippet with cmnts – Paul Rosemberg Sep 08 '15 at 14:52
  • while (reader.Read()) { int.TryParse(reader["id"].ToString(), out zid); name = reader["name"].ToString(); lstPayee.Items.Insert(idx++, name); listpayees.Add(new PAYEES(zid, name)); //left out during refacting } } ... finally { reader.Close(); conn1.Close(); payeecnt = idx; ////value set payeesArray = listpayees.ToArray(); //// was left out during refactoring } } – Paul Rosemberg Sep 08 '15 at 14:56
  • Sorry, I am having a hard time trying to edit code and end up hitting the enter key... – Paul Rosemberg Sep 08 '15 at 14:57
  • @PaulRosemberg The comments section is no place for code. Edit your question and add the code snippet with proper formatting. – Mihai Caracostea Sep 08 '15 at 19:56
0

Please close this post. I found the cause of the problem (and fixed it). I'd like to thank those who try and help. I'd like to learn how to format code when I post questions, the site mentions a tool in the toolbar but I could not find it...

Paul