Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is my ListBox throwing an exception?
    primarykey
    data
    text
    <p>Okay, I was able to create a simple Windows Forms project that reproduces some strange behavior I found. In the designer, make a form with a ListBox (named lbx) anchored Top, Left, Right, and Bottom, and a button (button1). Now, the Form's code is here:</p> <pre><code>using System; using System.Windows.Forms; namespace ListBoxKaboom { public partial class Form1 : Form { private bool _initFinished = false; public Form1() { InitializeComponent(); this._initFinished = true; this.Height += 100; this.Height -= 50; this.Height += 50; } private void lbx_SelectedIndexChanged(object sender, EventArgs e) { this.button1.Enabled = (this.lbx.SelectedItem != null); } protected override void OnLayout(LayoutEventArgs e) { if (_initFinished) { int lines = (this.lbx.Height - 4) / this.lbx.ItemHeight; this.SuspendLayout(); while (lines &lt; this.lbx.Items.Count) { this.lbx.Items.RemoveAt(this.lbx.Items.Count - 1); } while (lines &gt; this.lbx.Items.Count) { this.lbx.Items.Add("Item " + (this.lbx.Items.Count + 1).ToString()); } this.ResumeLayout(); } base.OnLayout(e); } } } </code></pre> <p>PLEASE NOTE THE FOLLOWING INSTRUCTIONS:</p> <p><strong>Run this, click any of the items in the list box, and use the arrow keys to move down far enough to cause the list box to scroll</strong>. Kaboom.</p> <p>Exception (sometimes NullReferenceException and sometimes IndexOutOfBoundsException). Any ideas why? Also, I would think that the items would be in order, but they're not. Is this just a goofy corner case that didn't get handled properly by Windows Forms, or am I doing something wrong?</p> <p>Stack trace:</p> <blockquote> <p>at System.Windows.Forms.ListBox.NativeUpdateSelection() <br/></p> <p>at System.Windows.Forms.ListBox.SelectedObjectCollection.EnsureUpToDate() <br/></p> <p>at System.Windows.Forms.ListBox.SelectedObjectCollection.get_InnerArray() <br/></p> <p>at System.Windows.Forms.ListBox.SelectedObjectCollection.get_Item(Int32 index) <br/></p> <p>at System.Windows.Forms.ListBox.get_SelectedItem() <br/></p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload