给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();   

你可能感兴趣的:(sql,server,C#,table,database,2010)