2012-09-16 60 views
1

我想每次使用組合框選擇項目更改時都使用對象屬性填充2個不同的文本框。我有以下代碼:使用combobox信息填充texbox

namespace WindowsFormsApplication5 
{ 
    public partial class Form1 : Form 
    {    
     Domicilio[] domicilios = new Domicilio[]{ 
      new Domicilio{Calle="balbin",Numero=469}, 
      new Domicilio{Calle="palacios",Numero=589}, 
      new Domicilio{Calle="rep arg",Numero=748}, 
      new Domicilio{Calle="escalada",Numero=562} 
     }; 

     public Form1() 
     { 
      InitializeComponent(); 
      foreach (var d in domicilios) 
      { 
       cbbDatoDomicilio.Items.Add(d); 
       cbbDatoDomicilio.DisplayMember = "Calle"; 
      }  
     }  
     protected override void OnLoad(EventArgs e) 
     { 
      base.OnLoad(e);       
     }  
     private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      // missing code here! 
      txtCalle.Text = d.Calle; 
      txtNumero.Text = d.Numero.ToString();     
     } 
    } 
} 

問題是我找不到填充它們的方法。代碼的問題是變量d超出了範圍,這就是爲什麼它不起作用。

回答

0

你必須你的方法中定義的變量d分配comboBox1

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
     Domicilio d = comboBox1.SelectedItem as Domicilio; 
     if (d!=null) 
     { 
     txtCalle.Text = d.Calle; 
     txtNumero.Text = d.Numero.ToString(); 
     } 
} 

的selectedItem屬性在另一方面,你可以考慮使用一個的BindingSource和訪問它的BindingSource。現任會員!! (看看How to: Bind a ListDataBinding example或MSDN How to: Bind a Windows Forms ComboBox