我有一个从数据库填充的下拉列表。当我只想在下拉列表的 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();
Run Code Online (Sandbox Code Playgroud)
您必须从数据库中选择“虚拟”列:
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();
Run Code Online (Sandbox Code Playgroud)