如何在组合框顶部插入项目? [英] How to insert item at the top of Combo Box?

查看:56
本文介绍了如何在组合框顶部插入项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Linq到SQl来绑定组合框控件.如何在组合框列表的顶部添加项目?

Hi I am using Linq to SQl to bind the combo box control. How can i add a item at the top of the list of combo box?

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--");

上面的代码失败.

推荐答案

一种方法是在绑定之前将"--Select--"联系人占位符插入结果中:

One way would be to insert the "--Select--" contact place-holder into the results before binding:

     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";

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

Or you could do the same thing with an anonymous version of the results:

     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";

这篇关于如何在组合框顶部插入项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆