添加“ALL”选项作为Combobox的第一选择

时间:2016-12-16 23:56:19

标签: c# .net winforms data-binding

我需要添加ALL选项作为组合框的首选。我在下面尝试过这个代码,但是All并没有添加,为了添加它,我必须改变什么?

string query = "select [empname] from [server].[dbo].[table]";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "tables");
cbotables.DisplayMember = "empname";
cbotables.Items.Insert(0, "All");
cbotables.DataSource = ds.Tables["tables"];

修改
我刚刚意识到我的代码中没有显示一些内容...我的连接字符串在上面声明,并且组合框的内容显示为应该从数据库中显示,而不是添加所有选项。

1 个答案:

答案 0 :(得分:1)

也许最简单的方法是在DataTable中插入一行,假设它的唯一作用是DataSource

// fill the datatable
dt.Load(cmd.ExecuteReader());

var dr = dt.NewRow();
dr["Id"] = -1;
dr["Name"] = "All";
dt.Rows.InsertAt(dr, 0);

cboEmp.DisplayMember = "Name";
cboEmp.ValueMember = "Id";
cboEmp.DataSource = dt;

更常见的是ValueMember这些,因此您可以告诉选择的内容,即“Id”列。如果DataTable有其他用途,您可能不希望向其添加虚假数据。为此,您可以将数据传输到匿名列表:

dt.Load(cmd.ExecuteReader());

// xfer data to anon collection
var myDS = dt.AsEnumerable()
    .Select(q => new {Name = q.Field<String>("Name"),
                      Value = q.Field<Int32>("Id") }
           )
    .ToList();

// add ALL with fake id
myDS.Insert(0, new { Name = "ALL", Value = -1 });

cboEmp.DisplayMember = "Name";
cboEmp.ValueMember = "Value";
cboEmp.DataSource = myDS;

无论哪种方式都会得到相同的结果:

enter image description here

如果你真的不需要Id,你不需要anon类型,只需选择名称和List<string>

相关问题