无法获得组合框选择的值

时间:2017-02-24 06:59:14

标签: c# combobox valuemember

这是我的代码 -

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

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

我错过了什么?

  

UPDATE -

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

2 个答案:

答案 0 :(得分:0)

也许您只是缺少combo.SelectedIndex = 0;

答案 1 :(得分:0)

您可能缺少DataSource属性:

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;