【问题标题】:How to add "All" option on top of the Combobox如何在组合框顶部添加“全部”选项
【发布时间】:2020-10-14 18:56:42
【问题描述】:

我需要添加“ALL”选项作为组合框的首选。我在下面尝试了这段代码,但没有工作。我得到的错误是“无法从 '' 转换为 ''” 我应该怎么做?请问我是这个员工的新手。

这是我的代码

private void LoadCountries()
        {
            try
            {
                using (Db db = new Db())
                {
                    var countries = (from u in db.Countries
                                     select new {Name =  u.CountryId, Value = u.CountryName }).ToList();


                    countries.Insert(0, new { Name = "All", Value = -1 }); // here I'am trying to add "All" Option

                    cmbCountry.DisplayMember = "CountryName";
                    cmbCountry.ValueMember = "CountryId";
                    cmbCountry.DataSource = countries;

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Exception inner = ex.InnerException;
                while (inner != null)
                {
                    MessageBox.Show(inner.Message);
                    inner = inner.InnerException;
                }
            }
        }

提前谢谢你

【问题讨论】:

  • I have tried this code below but npt working 什么不起作用?错误?
  • 有没有出现?我没想到会这样。您的匿名对象具有属性NameValue,但您将显示和值成员设置为CountryNameCountryId
  • @Jonesopolis 感谢您的回复。即使我没有像“select new { u.CountryName, u.CountryId }).ToList();”这样的属性来写我犯了同样的错误。我该怎么办 ?再次感谢并感谢您编写一些代码,这样我最容易理解。错误是“无法从 '' 转换为 ''”
  • @LarsTech,感谢您的回复。我得到的错误是“无法从 '' 转换为 ''”

标签: c# winforms combobox


【解决方案1】:

您要正确指定 DisplayMember 和 ValueMember 属性:

var countries = (from u in db.Countries
                 select new { Name =  u.CountryName, Value = u.CountryId }).ToList();

countries.Insert(0, new { Name = "All", Value = -1 }); 

cmbCountry.DisplayMember = "Name"; //use correct property name
cmbCountry.ValueMember = "Value";
cmbCountry.DataSource = countries;

【讨论】:

  • 现在用你的代码更新后,我得到最相似的错误“无法从''转换为''”
  • 我复制了你落后的属性。尝试更新
  • 太棒了,它正在工作。非常感谢。你拯救了我的一天......再次感谢你!
猜你喜欢
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2011-05-05
相关资源
最近更新 更多