Can't get combobox selected value

99 Views Asked by At

Here is my code -

combo.DisplayMember = "Caption";
combo.ValueMember = "PortName";
combo.Items.Add(new { PortName = "port", Caption = "caption"  });

//Null reference exception here-
String PortName = combo.SelectedValue.ToString();

What did I miss?

UPDATE-

//the following line has solved my problem-
dynamic item = cmbPortNo.SelectedItem;
string PortName = item.PortName;
2

There are 2 best solutions below

0
j.v. On

Maybe you just missing combo.SelectedIndex = 0; line

0
Sk Shahnawaz-ul Haque On

You might be missing the DataSource property:

List<CaptionPortCollection> list = new List<CaptionPortCollection>();
list.Add(new CaptionPortCollection() { Caption = "HTTP", Port = 80} );
list.Add(new CaptionPortCollection() { Caption = "HTTPS", Port = 443} );
...

combo.DisplayMember = "Caption";
combo.ValueMember = "Port";
combo.DataSource = list;