in the last line of the code im trying do casting but its return null. i mean selected = null. i wonder why and how can i fix it

StackOverflow https://stackoverflow.com/questions/22268013

Question

i have a class called LIstBoxItem which contain object A . later in the event im trying to approach this object. in order to do that im trying do casting but it return null. i mean selected = null. i wonder why and how can i fix it

class ListBoxItem
{
  A my_A;

  public ListBoxItem(A i_A)
  {
    my_A = i_A
  }

   public override string ToString()
            {
                return my_A.FirstName + " " + my_A.LastName;
            }
}

A m_CurrentA = new A( str1, str2 , , ,);
ListBoxItem new_ListBoxItem = new ListBoxGuestsItem(m_CurrentA);
this.listBox1.Items.Add(new_ListBoxItem);

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    { 
         ListBoxItem selected = sender as ListBoxItem;
             ...
    }
Was it helpful?

Solution

Sender is not the selected object, you must to get the selected object from listBox directly:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{ 
     ListBoxItem selected = listBox1.selectedItem as ListBoxItem;
}

or

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{ 
     ListBoxItem selected = listBox1.Items[listBox1.selectedIndex] as ListBoxItem;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top