【发布时间】:2013-03-04 18:26:55
【问题描述】:
我正在动态创建 Winforms 多选 ListBox 并将其添加到流程面板控件中。我从我创建的对象绑定数据源,并验证 DataSource 实际上确实有大约 14 个元素。当我执行listBox.SetSelected(0, true) 时,会抛出System.ArgumentOutOfRangeException 错误。
我已经确定问题在于,虽然 DataSource 有 14 个元素,但 Item 集合没有 (0),因此引发了异常。我的问题是为什么这两个彼此不同,为什么我不简单地将数据源中的 foreach 项目添加到项目集合中?
以下是我目前的代码:
case InsertableItemParameter.ParameterType.ListBox:
//note: two-way bindings are not possible with multiple-select listboxes
Label lblListBox = new Label();
lblListBox.Text = param.DisplayText;
ListBox listBox = new ListBox();
listBox.DataSource = param.Values;
listBox.DisplayMember = "Value";
listBox.SelectionMode = SelectionMode.MultiExtended;
listBox.Size = new System.Drawing.Size(flowPanel.Size.Width - lblListBox.Size.Width - 10, 100);
listBox.SetSelected(0, true); //will throw argument out of range exception here!
listBox.SetSelected(1, true);
flowPanel.Controls.Add(lblListBox);
flowPanel.Controls.Add(listBox);
flowPanel.SetFlowBreak(listBox, true);
break;
以下是我尝试和工作的替代解决方案,但为什么我要使用 DataSource 与 Items 集合?
case InsertableItemParameter.ParameterType.ListBox:
//note: two-way bindings are not possible with multiple-select listboxes
Label lblListBox = new Label();
lblListBox.Text = param.DisplayText;
ListBox listBox = new ListBox();
//listBox.DataSource = param.Values;
listBox.DisplayMember = "Value";
listBox.SelectionMode = SelectionMode.MultiExtended;
listBox.Size = new System.Drawing.Size(flowPanel.Size.Width - lblListBox.Size.Width - 10, 100);
listBox.BeginUpdate();
foreach (String paramater in param.Values)
{
listBox.Items.Add(paramater);
}
listBox.EndUpdate();
listBox.SetSelected(0, true);
listBox.SetSelected(1, true);
flowPanel.Controls.Add(lblListBox);
flowPanel.Controls.Add(listBox);
flowPanel.SetFlowBreak(listBox, true);
break;
回答:感谢所有回复。这里的问题是可见性和 win-form 渲染。虽然 DataSource 和 Items 集合之间的差异并没有真正解决(除了少数人),但我的问题的真正根源是通过在表单完成绘制后调用 SetSelected() 方法解决的。这在我的应用程序设计中引起了很多我必须解决的问题,但这就是问题所在。查看我标记为答案的回复。
【问题讨论】:
-
根据我对您帖子的了解,
ListBox.DataSource是 您的数据来自 来自 而ListBox.Item是您的数据已经有了。 -
@Brian 实际上,DataSource 是我拥有数据的地方,而 ListBox.Item 是完全空的。当我尝试使用简单的
listBox.Items.Add(paramater);将我的 DataSource 添加到我的 Item 集合中时,我收到一条错误消息,指出在设置 DataSource 时我无法将项目添加到 Item 集合中。 -
你能把所有的代码贴出来吗?
-
检查下面的答案,我相信它会帮助你,问题是你的控件在 DataSource 设置时不可见,这是一个已知的issue。只需将控件添加到父控件(以便将其设置为可见),然后您就可以设置选定的项目。
-
@Brad:我的猜测是因为许多控件在设计时是未知的,并且可以从 0 到无穷大不等。