【发布时间】:2009-09-08 20:05:39
【问题描述】:
好的,我能够创建一个简单的 Windows 窗体项目来重现我发现的一些奇怪行为。在设计器中,制作一个带有顶部、左侧、右侧和底部锚定的 ListBox(名为 lbx)和一个按钮 (button1) 的表单。现在,表单的代码在这里:
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 < this.lbx.Items.Count)
{
this.lbx.Items.RemoveAt(this.lbx.Items.Count - 1);
}
while (lines > this.lbx.Items.Count)
{
this.lbx.Items.Add("Item " + (this.lbx.Items.Count + 1).ToString());
}
this.ResumeLayout();
}
base.OnLayout(e);
}
}
}
请注意以下说明:
运行此程序,单击列表框中的任何项目,然后使用箭头键向下移动足够远以使列表框滚动。卡布姆。
异常(有时是 NullReferenceException,有时是 IndexOutOfBoundsException)。任何想法为什么?另外,我认为这些物品会井井有条,但事实并非如此。这只是 Windows 窗体没有正确处理的一个愚蠢的角落案例,还是我做错了什么?
堆栈跟踪:
在 System.Windows.Forms.ListBox.NativeUpdateSelection()
在 System.Windows.Forms.ListBox.SelectedObjectCollection.EnsureUpToDate()
在 System.Windows.Forms.ListBox.SelectedObjectCollection.get_InnerArray()
在 System.Windows.Forms.ListBox.SelectedObjectCollection.get_Item(Int32 索引)
在 System.Windows.Forms.ListBox.get_SelectedItem()
【问题讨论】:
-
请用堆栈信息发布异常。
-
我运行了代码,但没有收到异常。你得到什么样的异常,它是在哪里抛出的?
-
毫无例外,我怀疑我们能提供帮助。
-
由于在布局事件期间修改布局,这听起来像是重入问题。
-
您使 ListBox 受到它认为无法容忍的不自然行为。结果,它以它知道的唯一方式大声喊叫——除了一个例外。然而,当你把它逼疯的时候,它的叫声是不连贯的。为可怜的列表框哭泣;它没有做任何值得如此残忍的事情。