从Combobox中选择对象

时间:2013-09-02 17:07:12

标签: c# object combobox

我让这个Combobox充满了对象 从combobox中选择某个对象后,我想在Textbox中显示文字,但出于某种原因,我无法通过我的选择。

这就是我的combobox

 private void showBirds()
    {
        cboBirds.Items.Clear();
        foreach (Bird b in Bird.ReadBirdCSV(txtFile.Text))
        {
            cboBirds.Items.Add(b);
        }
    }

它基本上显示了物体鸟的鸟类名称。

 private void cboBirds_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

//WHAT DO I WRITE HERE TO GET txbGender TO SHOW THE GENDER?

        foreach (Bird b in cboBirds.Items)
        {
            Console.WriteLine(b.Gender +" - " + b.Name +" - " + b.Risk + " - " +b.Reference);
        }
//^This shows all info on every bird.

    }

我确信这很简单,我似乎无法弄明白。

1 个答案:

答案 0 :(得分:4)

使用ComboBox.SelectedIndexChanged事件

private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
     if(ComboBox1.SelectedItem==null) return;
     var b= (Bird) ComboBox1.SelectedItem;
     if(b!=null)
         Console.WriteLine(b.Gender +" - " + b.Name +" - " + b.Risk + " - " +b.Reference);
}