C# 如何在组合框中将第一个索引设置为空白

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18104541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:18:11  来源:igfitidea点击:

How to set first index as blank in combobox

c#winformsnhibernate

提问by Amit Kumar

I have a combobox that is bound with a datasource. In this combobox I have to add a blank field at index 0.

我有一个与数据源绑定的组合框。在这个组合框中,我必须在索引 0 处添加一个空白字段。

I have written following code for getting records.

我编写了以下代码来获取记录。

 public List<TBASubType> GetSubType(int typ)
        {
            using (var tr = session.BeginTransaction())
            {
                try
                {
                    List<TBASubType> lstSubTypes = (from sbt in session.Query<TBASubType>()
                                                    where sbt.FType == typ
                                                    select sbt).ToList();


                    tr.Commit();
                    return lstSubTypes;
                }
                catch (Exception ex)
                {
                    CusException cex = new CusException(ex);
                    cex.Write();
                    return null;
                }
            }
        }

After this it bind with combobox with data binding source as below code.

在此之后,它与具有数据绑定源的组合框绑定,如下代码所示。

M3.CM.BAL.CM CMobj = new M3.CM.BAL.CM(wSession.CreateSession());
                lstSubTypes = CMobj.GetSubType(type);
                this.tBASubTypeBindingSource.DataSource = lstSubTypes;

回答by Sergey Berezovskiy

Thus you can't modify Items when you are are bound to DataSource, then only option to add blank row is modifying your data source. Create some empty object and add it to data source. E.g. if you have list of some Personentities bound to combobox:

因此,当您绑定到 DataSource 时,您无法修改 Items,那么添加空白行的唯一选项就是修改您的数据源。创建一些空对象并将其添加到数据源。例如,如果您有一些Person绑定到组合框的实体列表:

var people = Builder<Person>.CreateListOfSize(10).Build().ToList();
people.Insert(0, new Person { Name = "" });
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = people;


You can define static property Emptyin your class:

您可以Empty在类中定义静态属性:

public static readonly Person Empty = new Person { Name = "" };

And use it to insert default blank item:

并使用它插入默认的空白项目:

people.Insert(0, Person.Empty);

This also will allow to check if selected item is default one:

这也将允许检查所选项目是否为默认项目:

private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    Person person = (Person)comboBox.SelectedItem;
    if (person == Person.Empty)
        MessageBox.Show("Default item selected!");
}    

回答by Energy

If you just want to select nothing initially, you can use

如果您最初只想不选择任何内容,则可以使用

comboBox1.SelectedIndex=-1;