Solved

ListBox.SelectedIndexCollection. Iteration failure.

Posted on 2003-11-27
13
992 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
  • 7
  • 4
  • 2
13 Comments
 
LVL 10

Expert Comment

by:smegghead
Comment Utility
This works fine for me...

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

Author Comment

by:moleInManc
Comment Utility
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
Comment Utility
bump
0
 
LVL 20

Expert Comment

by:TheAvenger
Comment Utility
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
Comment Utility
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
Comment Utility
It's automatically called, yoo don't have to do anything additionally.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 10

Expert Comment

by:smegghead
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks smeghead. I appreciate all of your help
0
 
LVL 10

Expert Comment

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

Smg
0
 

Author Comment

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

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

728 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

11 Experts available now in Live!

Get 1:1 Help Now