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

阿维拉姆·希里(Aviram Shiri)

我有一个名为LIstBoxItem的类,其中包含对象A。稍后,我会尝试接近该对象。为了做到这一点,我试图做铸造,但它返回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;
             ...
    }
marcin93w

发件人不是选定的对象,您必须直接从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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章