扩展方法:给 IEnumerable<TSource> 扩展一个自定义数据源绑定的方法

先给大家说一下,我要实现的效果。

 

直接贴代码了。

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

谢谢浏览!

转载于:https://www.cnblogs.com/Music/archive/2012/03/03/enumerable-extension-todatabind.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值