Reputation: 30303
I have a listbox control and I have to display a selected item in the listbox.
Here is code I have so far:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Clear();
foreach (object selectedItem in listBox1.SelectedItems)
{
textBox1.AppendText(selectedItem.ToString() + Environment.NewLine);
}
}
But it is giving me an error at foreach
.
Upvotes: 0
Views: 220
Reputation: 211
Try
foreach(object o in this.listBox1.SelectedItems)
{
aa.Add(selectedItem);
}
Upvotes: 1
Reputation: 150108
EDIT: The code you posted does not crash for me. The comment on this answer is correct, SelectedItems is empty, but not null, if no item is selected. Did you leave out some of the code to simplify things?
Check whether listBox1.SelectedItems is null first.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Clear();
if (listBox1.SelectedItems != null)
{
foreach (object selectedItem in listBox1.SelectedItems)
{
textBox1.AppendText(selectedItem.ToString() + Environment.NewLine);
}
}
}
Upvotes: 1