数据库的下拉列表,如何合并数据文本字段的列

本文关键字:数据 文本 字段 合并 下拉列表 何合并 数据库 | 更新日期: 2023-09-27 18:36:28

我有一个从数据库填充的下拉列表。当只想在下拉列表的数据文本字段中显示名字时,我让它工作。但是,如果我想显示 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();
您需要

定义一个自定义列:

SqlCommand cmd = new SqlCommand("SELECT CID, FirstName + ' ' + LastName AS [FormattedName] FROM tbl_customers", con);

然后,您可以直接绑定到该列:

CustomerList.DataTextFIeld = "FormattedName";

您可以使用数据库复制方法,同时连接等间距的列。

 string sql = @"SELECT FirstName + replicate(' ', 20 - len(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();