0
votes

I'm having some trouble figuring out why the .selectedItem or .SelectedValue properties for my databound combobox are always returning a null value. I'm new to programming, so I'm sure I'm making a simple mistake, but I was unable to find a solution online that worked.

Here's my code setting up a constructor:

class EngStnadardMOList
{
    public int ID { get; set; }
    public string Model { get; set; }

    public EngStnadardMOList(int i, string m)
    {
        ID = i;
        Model = m;  
    }
}

Then I populate on load:

public FrmEngStandardMO()
{
   InitializeComponent();
   fillList();
}

Here's the fillList() method:

private void fillList()
{
    List<EngStnadardMOList> _list = new List<EngStnadardMOList>() {

    new EngStnadardMOList(1,"PE1008B1R405-A-VA"),
    new EngStnadardMOList(2,"PE1008B1R405-A-VB"),
    new EngStnadardMOList(3,"PE103D1R420-A-VB"),
    new EngStnadardMOList(4,"PE103D1R420-A-VC"),
    new EngStnadardMOList(5,"PE105F1R420-A-VB"),
    new EngStnadardMOList(6,"PE105F1R420-A-VC"),
    new EngStnadardMOList(7,"PM108F2R420-A-VC"),
    new EngStnadardMOList(8,"PM112F3R4100-A-VC"),
    new EngStnadardMOList(9,"PM212F6R4200-A-VC")
};

    cmbStdModel.DisplayMember = "Model";
    cmbStdModel.ValueMember = "ID";
    cmbStdModel.DataSource = _list;

}

This does populate the combobox when you run the form, however, using the code below, I always get a null value when trying to get the selected item.

private void btnGenerateFiles_Click(object sender, EventArgs e)
{
   if (cmbStdModel.SelectedValue != null)
   {
       MessageBox.Show(cmbStdModel.Text);
   } 
   else {
       MessageBox.Show("Null Model.");
   }
        }  
    }

What am I doing wrong?

Thanks in advance!

1

1 Answers

2
votes

I've figured it out! I don't know why it works, but I found if I call the fillList(); method at the beginning of btnGenerateFiles_Click block, then the code doesn't return null.

I'm not sure why that is the case, so if anyone can clarify for me, I would appreciate it.