我需要将All作为可选择的选项添加到winform上的组合框的顶部。我已经尝试了下面的两个代码,其中一个不会抛出错误但是没有添加值:
public void GetData()
{
using (SqlConnection conn = new SqlConnection(SqlConnection))
{
SqlDataAdapter da = new SqlDataAdapter("select [empname] from [Testdb].[dbo].[Test] order by [empname] Asc", conn);
conn.Open();
da.Fill(ds, "Test");
cboemployees.Items.Insert(0, "All");
cboemployees.DisplayMember = "empname";
cboemployees.DataSource = ds.Tables["Test"];
}
}
现在这个语法会抛出错误
错误列'empname'不属于表
public void GetData()
{
using (SqlConnection conn = new SqlConnection(SqlConnection))
{
SqlDataAdapter da = new SqlDataAdapter("select [empname] from [Testdb].[dbo].[Test] order by [empname] Asc", conn);
conn.Open();
da.Fill(ds, "Test");
DataRow row = dt.NewRow();
row["empname"] = "All";
dt.Rows.InsertAt(row, -1);
cboemployees.DataSource = dt;
}
}
将可选项添加到绑定组合框顶部的正确方法是什么?
答案 0 :(得分:2)
将行添加到您的表格中。
SqlDataAdapter da = new SqlDataAdapter("select [empname] from [Testdb].[dbo].[Test] order by [empname] Asc", conn);
conn.Open();
da.Fill(ds, "Test");
// Add the row for All
var allRow = ds.Tables["Test"].NewRow();
allRow[0] = "All";
ds.Tables["Test"].Rows.InsertAt(allRow, 0);
cboemployees.DisplayMember = "empname";
cboemployees.DataSource = ds.Tables["Test"];