【问题标题】:Can't get combobox selected value无法获取组合框选定值
【发布时间】:2017-02-24 06:59:13
【问题描述】:

这是我的代码 -

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;

【问题讨论】:

  • 你有数据源吗?
  • 1.您在什么事件中获得了选定的值 2. 是否显示良好?

标签: c# combobox valuemember


【解决方案1】:

也许你只是错过了combo.SelectedIndex = 0; 行

【讨论】:

    【解决方案2】:

    您可能缺少 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 2013-10-27
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多