先给大家说一下,我要实现的效果。
直接贴代码了。
EnumerableExtension.cs
public static class EnumerableExtension
{
/// <summary>
/// 绑定数据
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TText"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="source"></param>
/// <param name="funcText"></param>
/// <param name="funcValue"></param>
/// <returns></returns>
public static IEnumerable<KeyValuePair<TText, TValue>> ToDataBind<TSource, TText, TValue>(this IEnumerable<TSource> source, Func<TSource, TText> funcText, Func<TSource, TValue> funcValue)
{
if(source == null)
{
throw new ArgumentNullException("source");
}
foreach (var item in source)
{
yield return new KeyValuePair<TText, TValue>(funcText(item), funcValue(item));
}
}
}
Product.cs
public class Product
{
public string ProductId { get; set; }
public string ProductName { get; set; }
public DateTime ProduceDate { get; set; }
}
ProductDB.cs
public class ProductDB
{
public static IList<Product> GetAllProducts()
{
return new List<Product>()
{
new Product(){ ProductId = "A00001", ProductName = "旺仔", ProduceDate = new DateTime(2012,1,18)},
new Product(){ ProductId = "A00002", ProductName = "营养快线", ProduceDate = new DateTime(2012,2,5)},
new Product(){ ProductId = "A00003", ProductName = "伊利纯牛奶", ProduceDate = new DateTime(2012,2,13)},
new Product(){ ProductId = "A00004", ProductName = "双汇王中王", ProduceDate = new DateTime(2012,2,17)},
new Product(){ ProductId = "A00005", ProductName = "康师傅绿茶", ProduceDate = new DateTime(2012,2,23)}
};
}
}
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
请选择产品:<asp:DropDownList ID="ddlProducts" runat="server" DataTextField="Key" DataValueField="Value">
</asp:DropDownList>
</div>
</form>
</body>
</html>
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
InitData();
}
}
protected void InitData()
{
this.ddlProducts.DataSource = ProductDB.GetAllProducts().ToDataBind(
u => "产品Id:" + u.ProductId
+ "; 产品名:" + u.ProductName
+ "; 生产日期:" + u.ProduceDate.ToString("yyyy-MM-dd HH:mm:ss"),
u => u.ProductId);
this.ddlProducts.DataBind();
}
}
Demo 下载:http://files.cnblogs.com/Music/DatabindExtension.rar
谢谢浏览!