在代码的最后一行我尝试进行转换但返回null。我的意思是选择= null。我想知道为什么以及如何解决它

时间:2014-03-08 10:19:32

标签: c# events listbox listboxitem

我有一个名为LIstBoxItem的类,它包含对象A.后来我试图接近这个对象。为了做到这一点我尝试做铸造,但它返回null。我的意思是选择= null。我想知道为什么以及如何解决它

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;
             ...
    }

1 个答案:

答案 0 :(得分:1)

发件人不是所选对象,您必须直接从listBox获取所选对象:

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

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{ 
     ListBoxItem selected = listBox1.Items[listBox1.selectedIndex] as ListBoxItem;
}