自定义控件(模板+数据绑定)先说说模板
<ASP:datagrid id="mydg" runat="server" >
<Columns>
<asp:Button id=Button1 Runat="server" >
</Columns>
</asp:datagrid>这个<Columns>就是个模板标记,在自定义控件中可以自己任意设置这个<Columns>,可以是<OverRed>...
开始:
新建个类
MyItemTemPlateC.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApp3
{
/// <summary>
/// MyTemplateC 的摘要说明。
/// </summary>
[ParseChildren(true)]
public class MyTemplateC: Control,INamingContainer
{
private ITemplate itemPlate;
[TemplateContainer(typeof(MyContainer))]
public ITemplate ItemTemplate
{
get{return itemPlate;}
set{itemPlate=value;}
}// private string text;
// public string Text
// {
// get{return text;}
// set{text=value;}
// }
private IEnumerable dataSource;
public IEnumerable DaTaSource
{
get{return this.dataSource;}
set{this.dataSource=value;}
} protected override void OnDataBinding(EventArgs e)
{
HasCreatDataSource();
//this.EnsureChildControls();//确定是否包含子控件,否则创建
/// <summary>
/// 为确保直到再次发生数据绑定时才创建子控件,在创建对象并将它添加到控件的
///ControlCollection 对象之后,将 ChildControlsCreated 属性设置为 true。
/// </summary>
this.ChildControlsCreated=true;
base.OnDataBinding (e);
}
protected override void CreateChildControls()
{
if(itemPlate!=null)
{ int itemCount=(int)ViewState["_itemCount"];
for(int i=0;i<itemCount;i++)
{ MyContainer myContainer=new MyContainer();
itemPlate.InstantiateIn(myContainer);//当由类实现时,创建子控件对象
this.Controls.Add(myContainer);
}
} else
{
this.Controls.Add(new LiteralControl(" NO TEMPLATE"));
}
} /// <summary>
/// 方法HasCreatDataSource作用是记录子控件的数目以及实例化子控件
/// </summary>
private void HasCreatDataSource()
{
if(itemPlate!=null)
{
int itemCount=0;//记录共创建多少个子控件
foreach(string s in dataSource)
{
MyContainer myContainer=new MyContainer();
myContainer.MyText(s);
itemPlate.InstantiateIn(myContainer);//当由类实现时,创建子控件对象
this.Controls.Add(myContainer);
itemCount++;
}
ViewState["_itemCount"]=itemCount;
}
else
{
this.Controls.Add(new LiteralControl(" NO TEMPLATE"));
}
}
}
public class MyContainer:Control,INamingContainer
{
private string text;
public string Text
{
get{return text;}
set{text=value;}
} public MyContainer()
{
//this.text=msg;
}
public string MyText(string msg)
{
this.text=msg;
return this.text;
}
}}