【问题标题】:Display blank instead of first item in combobox在组合框中显示空白而不是第一项
【发布时间】:2015-05-13 06:03:25
【问题描述】:

代码:

cmbItemType.DisplayMember = "Text";
cmbItemType.ValueMember = "Value";

var items = new[] {
        new { Text = "Text1", Value = "1"},  
        new { Text = "Text2", Value = "2"}
        };

cmbItemType.DataSource = items;

上面的代码显示了两个项目,但是如何在字段中显示一个空白项目。现在在加载时,它显示Text1 而不选择。我想显示一个空白项而不是Text1

注意空白项不应该添加到列表中,所以在选择combobox时,我不想查看Text1 上方的空白项 显示文本。谢谢。

【问题讨论】:

  • 添加另一个带有空白文本且值为 -1 或 0 的项目;
  • 请参阅我的问题中的 note。我不想将空白添加为列表。选择combobox时,它显示在Text1上方。

标签: c# .net winforms combobox


【解决方案1】:

将项目设置为数据源后:

cmbItemType.SelectedIndex = -1;

【讨论】:

    【解决方案2】:

    只需将ComboBoxSelectedIndex 设置为-1,它将向您显示没有从其项目列表中选择的任何项目的组合框。

    cmbItemType.DisplayMember = "Text";
    cmbItemType.ValueMember = "Value";
    
    var items = new[] {
        new { Text = "Text1", Value = "1"},  
        new { Text = "Text2", Value = "2"}
    };
    cmbItemType.DataSource = items;
    cmbItemType.SelectedIndex = -1; 
    

    注意:

    您不能将 ComboBox 项目的 SelectedIndex 设置为 -1,如果该项目 是一个数据绑定项。

    您可能有兴趣查找有关所选索引here 的更多信息。

    【讨论】:

      猜你喜欢
      • 2013-08-06
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多