Solved

ListBox.SelectedIndexCollection. Iteration failure.

Posted on 2003-11-27
13
1,030 Views
Last Modified: 2008-02-20
Hi All,

This has been giving me trouble for hours now and I have finally lost it. I am trying to establish which member of a Forms.Listbox are selected (MultiExtended selection mode). I have tried 2 implementations, both of which result in an array index out of bounds exception. Can anyone see why?

First and most sensible effort:.................................

ListBox.SelectedIndexCollection indexes = lstBoxPickable.SelectedIndices;

try
{
    foreach ( int index in indexes )
    {
        debugBox.Text += "" + index;
    }
}
catch (System.Exception)
{
    debugBox.Text = "D'oh. exception.";
}
            

****************************************************************

Getting desperate...

IEnumerator myEnum = indexes.GetEnumerator();

string current;

while(myEnum.MoveNext())
{
      current= (string)myEnum.Current;
      debugBox.Text += current;
}

***************************************************************

Any ideas appreciated.

Cheers
0
Comment
Question by:moleInManc
[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
  • 4
  • 2
13 Comments
 
LVL 10

Expert Comment

by:smegghead
ID: 9834756
This works fine for me...

      foreach (int Index in listBox1.SelectedIndices)
      {
            MessageBox.Show(Index.ToString());
      }
0
 

Author Comment

by:moleInManc
ID: 9835735
Thats why I have been pulling my hair out because thats how it is supposed to wor. Unfortunately for me I get: An unhandled exception of type 'System.IndexOutOfRangeException' occurred in system.windows.forms.dll everytime I try and run the blasted thing!
0
 

Author Comment

by:moleInManc
ID: 9836142
bump
0
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
LVL 20

Expert Comment

by:TheAvenger
ID: 9836293
I think the problem is in another porstion of the code. Can you post something more? You don't use any indexing here so this exeption is not expected...
0
 

Author Comment

by:moleInManc
ID: 9836410
yes, you are right. Its the fact that I am handling the mousedown event in the listbox to implement some drag and drop. I assume that this event is used by the listbox to handle the addition of new selections to selected collection. How can I call the default handler in my overridden portion?
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 9836458
It's automatically called, yoo don't have to do anything additionally.
0
 
LVL 10

Expert Comment

by:smegghead
ID: 9836898
So, When you mouse down, it's at that stage that you want to determine the selected entries ??

Have you actually overriden the mousedown function or are you just consuming the event ?

For the purposes of getting this working, I'd remove all your try/catch blocks.

I would only use try/catch if you are calling something that is out of your control, like a file/database access. That way you can see exactly where the error occurs, and you can examine variable values.

If you are still having problems, can you post some more of your code.. like the actual point where it is falling over.

Chrs
Smg.
0
 

Author Comment

by:moleInManc
ID: 9837095
Hi, yes I'm still having problems. I know this is simple but somehow my brain won't accept that argument. I have pasted my code in below. It works after a fashion but in order to drag something you have to select it and then reselect it for the drag. Thats maybe not so bad but what is unacceptable is that if you drag "One" "Two" and "Three" to one of the empty boxes - then select, maybe "Six" the wrong index is report!!

Any comments suggestions. Thanks for you help on this

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
using System.Text;

namespace Packing
{
      /// <summary>
      /// Summary description for Export.
      /// </summary>
      public class FrmExport : System.Windows.Forms.Form
      {
            private System.Windows.Forms.Label lblSelect;
            private System.Windows.Forms.ListBox lstBoxPickable;
            private System.Windows.Forms.ListBox lstBoxOp1;
            private System.Windows.Forms.ListBox lstBoxOp2;
            private System.Windows.Forms.ListBox lstBoxOp3;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            private ListBox.SelectedIndexCollection selectedList = null;
            private int lastSelection = -1;
            
            public FrmExport()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();
                  
                  lstBoxPickabel.Items.Add("One");
                                                lstBoxPickabel.Items.Add("Two");
                                                lstBoxPickabel.Items.Add("Three);
                                                lstBoxPickabel.Items.Add("Four");
                                                lstBoxPickabel.Items.Add("Five");
                                                lstBoxPickabel.Items.Add("Six");      
                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if(components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.lblSelect = new System.Windows.Forms.Label();
                  this.lstBoxPickable = new System.Windows.Forms.ListBox();
                  this.lstBoxOp1 = new System.Windows.Forms.ListBox();
                  this.lstBoxOp2 = new System.Windows.Forms.ListBox();
                  this.lstBoxOp3 = new System.Windows.Forms.ListBox();
                  this.SuspendLayout();
                  //
                  // lblSelect
                  //
                  this.lblSelect.Location = new System.Drawing.Point(48, 24);
                  this.lblSelect.Name = "lblSelect";
                  this.lblSelect.Size = new System.Drawing.Size(112, 16);
                  this.lblSelect.TabIndex = 0;
                  this.lblSelect.Text = "Select orders to pick:";
                  //
                  // lstBoxPickable
                  //
                  this.lstBoxPickable.Location = new System.Drawing.Point(48, 48);
                  this.lstBoxPickable.Name = "lstBoxPickable";
                  this.lstBoxPickable.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
                  this.lstBoxPickable.Size = new System.Drawing.Size(184, 134);
                  this.lstBoxPickable.TabIndex = 1;
                  this.lstBoxPickable.MouseDown += new System.Windows.Forms.MouseEventHandler(this.OnPickListMouseDown);
                  this.lstBoxPickable.SelectedIndexChanged += new System.EventHandler(this.OnSelectionChanged);
                  //
                  // lstBoxOp1
                  //
                  this.lstBoxOp1.AllowDrop = true;
                  this.lstBoxOp1.Location = new System.Drawing.Point(16, 216);
                  this.lstBoxOp1.Name = "lstBoxOp1";
                  this.lstBoxOp1.Size = new System.Drawing.Size(136, 173);
                  this.lstBoxOp1.TabIndex = 2;
                  this.lstBoxOp1.DragDrop += new System.Windows.Forms.DragEventHandler(this.OnDragDrop);
                  this.lstBoxOp1.DragEnter += new System.Windows.Forms.DragEventHandler(this.OnDragEnter);
                  //
                  // lstBoxOp2
                  //
                  this.lstBoxOp2.AllowDrop = true;
                  this.lstBoxOp2.Location = new System.Drawing.Point(176, 216);
                  this.lstBoxOp2.Name = "lstBoxOp2";
                  this.lstBoxOp2.Size = new System.Drawing.Size(136, 173);
                  this.lstBoxOp2.TabIndex = 3;
                  this.lstBoxOp2.DragDrop += new System.Windows.Forms.DragEventHandler(this.OnDragDrop);
                  this.lstBoxOp2.DragEnter += new System.Windows.Forms.DragEventHandler(this.OnDragEnter);
                  //
                  // lstBoxOp3
                  //
                  this.lstBoxOp3.AllowDrop = true;
                  this.lstBoxOp3.Location = new System.Drawing.Point(336, 216);
                  this.lstBoxOp3.Name = "lstBoxOp3";
                  this.lstBoxOp3.Size = new System.Drawing.Size(136, 173);
                  this.lstBoxOp3.TabIndex = 4;
                  this.lstBoxOp3.DragDrop += new System.Windows.Forms.DragEventHandler(this.OnDragDrop);
                  this.lstBoxOp3.DragEnter += new System.Windows.Forms.DragEventHandler(this.OnDragEnter);
                  //
                  // FrmExport
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(488, 446);
                  this.Controls.Add(this.lstBoxOp3);
                  this.Controls.Add(this.lstBoxOp2);
                  this.Controls.Add(this.lstBoxOp1);
                  this.Controls.Add(this.lstBoxPickable);
                  this.Controls.Add(this.lblSelect);
                  this.Name = "FrmExport";
                  this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
                  this.Text = "Pickable";
                  this.ResumeLayout(false);

            }
            #endregion

            private void OnPickListMouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
            {      
                  if ( lstBoxPickable.SelectedIndices.Equals(selectedList) )
                  {
                              lstBoxPickable.DoDragDrop(lstBoxPickable.SelectedItems.ToString(), DragDropEffects.Copy);
                  }
                  
                  lastSelection = -1;
            }

            private void OnDragEnter(object sender, System.Windows.Forms.DragEventArgs e)
            {
                  //ensure that dragged data is suitable i.e text
                  if (e.Data.GetDataPresent(DataFormats.Text, true))
                  {
                        e.Effect = DragDropEffects.Copy;
                  }
            }

            private void OnDragDrop(object sender, System.Windows.Forms.DragEventArgs e)
            {      
                  foreach (int Index in lstBoxPickable.SelectedIndices)
                  {
                        MessageBox.Show(Index.ToString());
                  }
            }

            private void OnSelectionChanged(object sender, System.EventArgs e)
            {
                  selectedList = lstBoxPickable.SelectedIndices;
            }
      }
}
0
 

Author Comment

by:moleInManc
ID: 9837099
Sorry theres a typo in the above :

 public FrmExport()
          {
               //
               // Required for Windows Form Designer support
               //
               InitializeComponent();
               
               lstBoxPickable.Items.Add("One");
                                                lstBoxPickabel.Items.Add("Two");
                                                lstBoxPickabel.Items.Add("Three);
                                                lstBoxPickabel.Items.Add("Four");
                                                lstBoxPickabel.Items.Add("Five");
                                                lstBoxPickabel.Items.Add("Six");    
               //
               // TODO: Add any constructor code after InitializeComponent call
               //
          }

0
 
LVL 10

Accepted Solution

by:
smegghead earned 50 total points
ID: 9837308
I've changed a few bits and pieces.. this should work.

I think your problem was that you were calling dodragdrop as soon as the mouse was pressed, which confused it..

HTH

Smg..

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
using System.Text;

namespace Packing
{
      /// <summary>
      /// Summary description for Export.
      /// </summary>
      public class FrmExport : System.Windows.Forms.Form
      {
            private System.Windows.Forms.Label lblSelect;
            private System.Windows.Forms.ListBox lstBoxPickable;
            private System.Windows.Forms.ListBox lstBoxOp1;
            private System.Windows.Forms.ListBox lstBoxOp2;
            private System.Windows.Forms.ListBox lstBoxOp3;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            private ListBox.SelectedIndexCollection selectedList = null;
            private int lastSelection = -1;
         
            public FrmExport()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();
               
                  lstBoxPickable.Items.Add("One");
                  lstBoxPickable.Items.Add("Two");
                  lstBoxPickable.Items.Add("Three");
                  lstBoxPickable.Items.Add("Four");
                  lstBoxPickable.Items.Add("Five");
                  lstBoxPickable.Items.Add("Six");    
                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if(components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            [STAThread]
            static void Main()
            {
                  Application.Run(new FrmExport());
            }


          #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.lblSelect = new System.Windows.Forms.Label();
                  this.lstBoxPickable = new System.Windows.Forms.ListBox();
                  this.lstBoxOp1 = new System.Windows.Forms.ListBox();
                  this.lstBoxOp2 = new System.Windows.Forms.ListBox();
                  this.lstBoxOp3 = new System.Windows.Forms.ListBox();
                  this.SuspendLayout();
                  //
                  // lblSelect
                  //
                  this.lblSelect.Location = new System.Drawing.Point(48, 24);
                  this.lblSelect.Name = "lblSelect";
                  this.lblSelect.Size = new System.Drawing.Size(112, 16);
                  this.lblSelect.TabIndex = 0;
                  this.lblSelect.Text = "Select orders to pick:";
                  //
                  // lstBoxPickable
                  //
                  this.lstBoxPickable.Location = new System.Drawing.Point(48, 48);
                  this.lstBoxPickable.Name = "lstBoxPickable";
                  this.lstBoxPickable.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
                  this.lstBoxPickable.Size = new System.Drawing.Size(184, 134);
                  this.lstBoxPickable.TabIndex = 1;
                  this.lstBoxPickable.MouseDown += new System.Windows.Forms.MouseEventHandler(this.OnPickListMouseDown);
                  this.lstBoxPickable.MouseMove += new System.Windows.Forms.MouseEventHandler(this.lstBoxPickable_MouseMove);
                  //
                  // lstBoxOp1
                  //
                  this.lstBoxOp1.AllowDrop = true;
                  this.lstBoxOp1.Location = new System.Drawing.Point(16, 216);
                  this.lstBoxOp1.Name = "lstBoxOp1";
                  this.lstBoxOp1.Size = new System.Drawing.Size(136, 173);
                  this.lstBoxOp1.TabIndex = 2;
                  this.lstBoxOp1.DragDrop += new System.Windows.Forms.DragEventHandler(this.OnDragDrop);
                  this.lstBoxOp1.DragEnter += new System.Windows.Forms.DragEventHandler(this.OnDragEnter);
                  //
                  // lstBoxOp2
                  //
                  this.lstBoxOp2.AllowDrop = true;
                  this.lstBoxOp2.Location = new System.Drawing.Point(176, 216);
                  this.lstBoxOp2.Name = "lstBoxOp2";
                  this.lstBoxOp2.Size = new System.Drawing.Size(136, 173);
                  this.lstBoxOp2.TabIndex = 3;
                  this.lstBoxOp2.DragDrop += new System.Windows.Forms.DragEventHandler(this.OnDragDrop);
                  this.lstBoxOp2.DragEnter += new System.Windows.Forms.DragEventHandler(this.OnDragEnter);
                  //
                  // lstBoxOp3
                  //
                  this.lstBoxOp3.AllowDrop = true;
                  this.lstBoxOp3.Location = new System.Drawing.Point(336, 216);
                  this.lstBoxOp3.Name = "lstBoxOp3";
                  this.lstBoxOp3.Size = new System.Drawing.Size(136, 173);
                  this.lstBoxOp3.TabIndex = 4;
                  this.lstBoxOp3.DragDrop += new System.Windows.Forms.DragEventHandler(this.OnDragDrop);
                  this.lstBoxOp3.DragEnter += new System.Windows.Forms.DragEventHandler(this.OnDragEnter);
                  //
                  // FrmExport
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(488, 446);
                  this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                                                              this.lstBoxOp3,
                                                                                                              this.lstBoxOp2,
                                                                                                              this.lstBoxOp1,
                                                                                                              this.lstBoxPickable,
                                                                                                              this.lblSelect});
                  this.Name = "FrmExport";
                  this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
                  this.Text = "Pickable";
                  this.ResumeLayout(false);

            }
          #endregion

            private Point LastPoint;

            private void OnPickListMouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
            {    
                  LastPoint=MousePosition;
            }

            private void OnDragEnter(object sender, System.Windows.Forms.DragEventArgs e)
            {
                  //ensure that dragged data is suitable i.e text
                  if (e.Data.GetDataPresent(DataFormats.Text, true))
                  {
                        e.Effect = DragDropEffects.Copy;
                  }
            }


            private void OnDragDrop(object sender, System.Windows.Forms.DragEventArgs e)
            {    
                  foreach (int Index in lstBoxPickable.SelectedIndices)
                  {
                        Console.WriteLine(Index.ToString());
                  }
            }


            private void lstBoxPickable_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
            {
                  if (e.Button==MouseButtons.Left)
                  {
                        if (PointCompare(LastPoint,MousePosition)>8) // We've moved the mouse 8 pixels away from original point
                        {
                              lstBoxPickable.DoDragDrop(lstBoxPickable.SelectedItems.ToString(), DragDropEffects.Copy);
                        }
                  }
            }

            public int PointCompare(Point One,Point Two)
            {
                  return Math.Abs(One.X-Two.X)+Math.Abs(One.Y-Two.Y);
            }

      }
}
0
 

Author Comment

by:moleInManc
ID: 9837448
Thanks smeghead. I appreciate all of your help
0
 
LVL 10

Expert Comment

by:smegghead
ID: 9837716
no problem.. but grade 'b' ??? where did I go wrong ?

Smg
0
 

Author Comment

by:moleInManc
ID: 9837745
my bad, sloppy mouse clicky... long lunch ;~)
0

Featured Post

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

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…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

688 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