gpt4 book ai didi

c# - 如何在组合框的顶部插入项目?

转载 作者:行者123 更新时间:2023-11-30 13:33:46 25 4
gpt4 key购买 nike

您好,我正在使用 Linq to SQl 来绑定(bind)组合框控件。如何在组合框列表的顶部添加项目?

var items = from c in db.Contacts
orderby c.Name ascending
select c;
if (items.ToList().Count > 0)
{
cmb1.BindingContext = new BindingContext();
cmb1.DataSource = items;
cmb1.DisplayMember = "Name";
cmb1.ValueMember = "ID";
}

cmb1.Items.Insert(0, "--Select--");

上面的代码失败了。

最佳答案

一种方法是在绑定(bind)之前将“--Select--”联系人占位符插入到结果中:

     var items = (from c in db.Contacts
orderby c.Name ascending
select c).ToList();

items.Insert(0, new Contact { ID = 0, Name = "--Select--" });

cmb1.BindingContext = new BindingContext();
cmb1.DataSource = items;
cmb1.DisplayMember = "Name";
cmb1.ValueMember = "ID";

或者您可以对结果的匿名版本执行相同的操作:

     var items = (from c in db.Contacts
orderby c.Name ascending
select new { c.ID, c.Name }).ToList();

items.Insert(0, new { ID = 0, Name = "--Select--" });

cmb1.BindingContext = new BindingContext();
cmb1.DataSource = items;
cmb1.DisplayMember = "Name";
cmb1.ValueMember = "ID";

关于c# - 如何在组合框的顶部插入项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5518233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com