tags:

views:

58

answers:

3

i have listbox control and i have to display selected item in the listbox.

some one send the code. the code like below

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 errow at foreach please help me

+1  A: 

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); 
        } 
    }
}
Eric J.
`SelectedItems` is never null, you would probably want to check the count instead: `if (listBox1.SelectedItems.Count > 0)`
Fredrik Mörk
I stand corrected. Just tested the code and it does not crash as posted.
Eric J.
+1  A: 

Try foreach(object o in this.listBox1.SelectedItems) { aa.Add(selectedItem); }

Alynuzzu
How is that any different compared to the code of the topicstarter (besides the redundant use of 'this' ) ?
Frederik Gheysels
Where does `selectedItem` come from if your loop is using a variable `o`?
Pierre-Alain Vigeant
I think that for reasons unknown to me, you do not run your event. Yes, I added this
Alynuzzu
A: 

There is not enough information here to answer the question, please post a sample of the error message you receive

krystan honour