Winformsの複数選択リストボックスを動的に作成し、それをフローパネルコントロールに追加しています。作成したオブジェクトからデータソースをバインドし、データソースに実際に約14個の要素があることを確認しました。実行するlistBox.SetSelected(0, true)
と、System.ArgumentOutOfRangeException
エラーがスローされます。
問題は、データソースには14個の要素がありますが、アイテムコレクションには何も(0)がないため、例外がスローされることであると判断しました。私の質問は、なぜこれら2つが互いに異なるのか、そしてなぜデータソースの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;
以下は、私が試し、実行した代替ソリューションですが、なぜデータソースとアイテムのコレクションを使用するのでしょうか。
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;
回答:すべての回答に感謝します。ここでの問題は、可視性とウィンフォームレンダリングです。DataSourceコレクションとItemsコレクションの違いは、少数の人を除いて実際には対処されていませんでしたがSetSelected()
、フォームの描画が完了した後にメソッドを呼び出すことで、私の問題の本当の原因は解決されました。これにより、アプリケーションの設計で解決しなければならない多くの問題が発生しますが、これが問題でした。私が答えとしてマークした返信を参照してください。