这是我的代码 -
combo.DisplayMember = "Caption";
combo.ValueMember = "PortName";
combo.Items.Add(new { PortName = "port", Caption = "caption" });
//Null reference exception here-
String PortName = combo.SelectedValue.ToString();
我想念什么?
更新 -
//the following line has solved my problem- dynamic item = cmbPortNo.SelectedItem; string PortName = item.PortName;
也许您只是缺少 combo.SelectedIndex = 0;
line
您可能会缺少数据源属性:
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;