我有一个从数据库中填充的下拉列表。当只想在下拉列表的DataTextField中显示名字时,它可以工作。但是,如果我想显示2个字段,名字和姓氏,则抛出错误。为什么这不起作用,或者我如何使其起作用?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_customers", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
da.Fill(ds, "Customers");
CustomerList.DataSource = ds.Tables[0];
CustomerList.DataTextField = "FirstName" + " " + "LastName";
CustomerList.DataValueField = "CID";
CustomerList.DataBind();
最佳答案
您必须从数据库中选择“虚拟”列:
string sql = @"SELECT FirstName + ' ' + LastName AS FullName,
CID, FirstName, LastName
FROM tbl_customers
ORDER BY FullName ASC;"
SqlCommand cmd = new SqlCommand(sql, con);
// ...
CustomerList.DataSource = ds.Tables[0];
CustomerList.DataTextField = "FullName";
CustomerList.DataValueField = "CID";
CustomerList.DataBind();
关于c# - db的下拉列表,如何为DataTextField合并列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19522112/