Click here to Skip to main content
15,886,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
if (reader.Read())
{
  listView2.Items.Add(reader["YearLabel"].ToString());
  foreach (ListViewItem item1 in listView1.Items)
  {
    if (reader.HasRows)
    {
        dt.Load(reader);
        sda.Fill(dt);
    }
    int i;
    for (i = 0; i <= dt.Rows.Count - 1; i++)
    {
      listView2.Items.Add(dt.Rows[i].ItemArray[0].ToString());
      if (listView2.SelectedItems.Count > 0)
      {
        for (i = 0; i <= listView2.Items.Count - 1; i++)
        {
            if (listView2.Items[i].Selected == true)
            {
              break;
            }
        }
      }
      //listView2.Items[i].SubItems.Add(dt.Rows[i].ItemArray[1].ToString());
      StringBuilder sb = new StringBuilder();
      for (i = 0; i < listView2.Items.Count ; i++)
      {
        for (int j = 1; j < listView2.Items.Count; j++)
        {
          this.listView2.View = View.Tile;
          if (i == j)
          {
              if (listView2.Items[i].Text != listView2.Items[j].Text)
              {
                  sb.AppendLine(listView1.Items[j].Text);
                  listView2.Items[j].Remove();
              }
          }
        }
      }
//[...]
    }
  }
}
Posted
Updated 10-Mar-15 20:38pm
v2
Comments
StM0n 11-Mar-15 2:39am    
Where does your error appear? You're using indices twice...

1 solution

You're removing items from the list you're going through...so you remove one item, the count is no longer valid, indexes change and you get an overflow.

Correct implementation is to set list count into a variable and each time you remove an item, decrease the count by one so you'll never exceed maximum length.

Alternatively, you could go through listView2 adding items to listView1 and then go through listView1 deleting things from listView2.

If this helps please take time do accept the solution. Thank you.
 
Share this answer
 
Comments
Richard MacCutchan 11-Mar-15 4:22am    
Alternative implementation is to do it in reverse order.
Sinisa Hajnal 11-Mar-15 7:42am    
Every day you learn something new :) I never thought of that.
Richard MacCutchan 11-Mar-15 7:52am    
I usually discover things like that after spending a day hitting my head against a brick wall. :)
Sinisa Hajnal 11-Mar-15 8:23am    
Happened to me too :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900