如何在ComboBox中将第一个索引设置为空?

19

我有一个绑定了数据源的组合框。在这个组合框中,我需要在索引0处添加一个空字段。

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

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

接下来,它将与数据绑定源为以下代码的组合框进行绑定。

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

1
在你的绑定源中包含一个空字符串记录吗? - Mathieu Guindon
4个回答

36

如果您希望最初不选择任何内容,您可以使用

comboBox1.SelectedIndex=-1;

2
不,我想在组合框中添加一个空白行。 - Amit Kumar

17
因此,当您绑定到数据源时无法修改项目,因此添加空行的唯一选项是修改数据源。创建一些空对象并将其添加到数据源中。例如,如果您有一些绑定到组合框的Person实体列表:
var people = Builder<Person>.CreateListOfSize(10).Build().ToList();
people.Insert(0, new Person { Name = "" });
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = people;

您可以在类中定义静态属性Empty:
public static readonly Person Empty = new Person { Name = "" };

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

people.Insert(0, Person.Empty);

这还可以检查所选项目是否为默认项:
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    Person person = (Person)comboBox.SelectedItem;
    if (person == Person.Empty)
        MessageBox.Show("Default item selected!");
}    

0
        cboCustomers.Items.Add(""); // Just add a blank item first

        // Then load the records from the database
        try
        {
            OleDbConnection con = new OleDbConnection(strDBConnection);
            OleDbCommand cmd = new OleDbCommand();
            con.Open();
            cmd.Connection = con;
            cmd.CommandText = "SELECT * FROM Customers";
            OleDbDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                cboCustomers.Items.Add(dr["Name"]);
            }
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

0
在创建完我的组合框之后,我将以下代码添加到Load()方法的末尾:
private void xyz_Load(object sender, EventArgs e)
{
    this.xyzTableAdapter.Fill(this.DataSet.xyz);
    this.comboBoxXYZ.SelectedIndex = -1;
}

用你为控件命名的名称替换xyz


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接