给DropDownList的DataTextField属性绑定两个字段

给DropDownList的DataTextField属性绑定两个字段
2010年01月03日 星期日 20:29

方法1:在SQL查询语句中拼接字段

 

C#代码
  1. using (SqlConnection conn = new SqlConnection("server=(local);database=Northwind;user id=sa;password=sa;min pool size=4;max pool size=100;Connection Lifetime=30;"))   
  2. {   
  3.      SqlDataAdapter adapter1 = new SqlDataAdapter("Select Top 10 ProductId,ProductName+','+convert(nvarchar,UnitPrice) Text FROM Products", conn);   
  4.      DataTable table1 = new DataTable();   
  5.      adapter1.Fill(table1);   
  6.   
  7.      DropDownList1.DataSource = table1.DefaultView;   
  8.      DropDownList1.DataTextField = "Text";   
  9.      DropDownList1.DataValueField = "ProductId";   
  10.      DropDownList1.DataBind();   
  11. }  

 

 

 

方法2:在DataTable中新增一字段

 

 

C#代码
  1. using (SqlConnection conn = new SqlConnection("server=(local);database=Northwind;user id=sa;password=sa;min pool size=4;max pool size=100;Connection Lifetime=30;"))   
  2. {   
  3.      SqlDataAdapter adapter1 = new SqlDataAdapter("Select Top 10 ProductId,ProductName,UnitPrice FROM Products", conn);   
  4.      DataTable table1 = new DataTable();   
  5.      adapter1.Fill(table1);   
  6.   
  7.      table1.Columns.Add("Text", System.Type.GetType("System.String"), "ProductName+'-'+UnitPrice");   
  8.   
  9.      DropDownList1.DataSource = table1.DefaultView;   
  10.      DropDownList1.DataTextField = "Text";   
  11.      DropDownList1.DataValueField = "ProductId";   
  12.      DropDownList1.DataBind();   
posted @ 2011-06-24 09:53  灵雨飘零  阅读(5196)  评论(0编辑  收藏  举报