li.的博客
li.的首页 > li.的博客 > 浏览文章

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

分类:.net应用  人气:811  评论:0  时间:2010-10-20 15:55

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


C#代码
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;"))   
{   
     SqlDataAdapter adapter1 = new SqlDataAdapter("Select Top 10 ProductId,ProductName+','+convert(nvarchar,UnitPrice) Text FROM Products", conn);   
     DataTable table1 = new DataTable();   
     adapter1.Fill(table1);   
  
     DropDownList1.DataSource = table1.DefaultView;   
     DropDownList1.DataTextField = "Text";   
     DropDownList1.DataValueField = "ProductId";   
     DropDownList1.DataBind();   
}  

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;"))
{
    SqlDataAdapter adapter1 = new SqlDataAdapter("Select Top 10 ProductId,ProductName+','+convert(nvarchar,UnitPrice) Text FROM Products", conn);
    DataTable table1 = new DataTable();
    adapter1.Fill(table1);

    DropDownList1.DataSource = table1.DefaultView;
    DropDownList1.DataTextField = "Text";
    DropDownList1.DataValueField = "ProductId";
    DropDownList1.DataBind();
}

 

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

 

C#代码
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;"))   
{   
     SqlDataAdapter adapter1 = new SqlDataAdapter("Select Top 10 ProductId,ProductName,UnitPrice FROM Products", conn);   
     DataTable table1 = new DataTable();   
     adapter1.Fill(table1);   
  
     table1.Columns.Add("Text", System.Type.GetType("System.String"), "ProductName+'-'+UnitPrice");   
  
     DropDownList1.DataSource = table1.DefaultView;   
     DropDownList1.DataTextField = "Text";   
     DropDownList1.DataValueField = "ProductId";   
     DropDownList1.DataBind();   
}

 

方法3:在使用for循环

评论(0)
暂无评论
我来评论
(800字以内)