1

I am trying to populate 2 different textboxes with the objects properties everytime the combobox selected item changes. I have the following code:

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();                
        }
    }
}

The problem is that I can't find a way of populating them. The problem with the code is that the variable d is out of scope and that's why it doesn't work.

Pilgerstorfer Franz
  • 8,303
  • 3
  • 41
  • 54
d-railed
  • 56
  • 3

1 Answers1

0

You have to define your variable d within your method and assign the selectedItem of 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();
      }
 }

On the other hand you may consider using a bindingSource and accessing it's BindingSource.Current member!! (have a look at How to: Bind a List or DataBinding example or MSDN How to: Bind a Windows Forms ComboBox

Community
  • 1
  • 1
Pilgerstorfer Franz
  • 8,303
  • 3
  • 41
  • 54