为DataGrid动态创建模板列,首先要实现ITemplate接口:
public
class
MyDataGridTemplate : System.Web.UI.ITemplate
... {
ListItemType _litType;
object _objData;
public MyDataGridTemplate(ListItemType litType, object objData)
...{
_litType = litType;
_objData = objData;
}
public void InstantiateIn(System.Web.UI.Control container)
...{
Literal ltr = new Literal();
TextBox txt = new TextBox();
switch(_litType)
...{
case ListItemType.Header:
ltr.Text = "<b>" + _objData.ToString() + "</b>";
container.Controls.Add(ltr);
break;
case ListItemType.Item:
ltr.Text = _objData.ToString();
container.Controls.Add(ltr);
break;
case ListItemType.EditItem:
container.Controls.Add(txt);
break;
case ListItemType.Footer:
ltr.Text = "<i>" + _objData.ToString() + "</i>";
container.Controls.Add(ltr);
break;
}
}
}
... {
ListItemType _litType;
object _objData;
public MyDataGridTemplate(ListItemType litType, object objData)
...{
_litType = litType;
_objData = objData;
}
public void InstantiateIn(System.Web.UI.Control container)
...{
Literal ltr = new Literal();
TextBox txt = new TextBox();
switch(_litType)
...{
case ListItemType.Header:
ltr.Text = "<b>" + _objData.ToString() + "</b>";
container.Controls.Add(ltr);
break;
case ListItemType.Item:
ltr.Text = _objData.ToString();
container.Controls.Add(ltr);
break;
case ListItemType.EditItem:
container.Controls.Add(txt);
break;
case ListItemType.Footer:
ltr.Text = "<i>" + _objData.ToString() + "</i>";
container.Controls.Add(ltr);
break;
}
}
}
现在就可以动态创建模板列了:
TemplateColumn tc;
tc = new TemplateColumn();
tc.HeaderText = " 列1 " ;
tc.ItemTemplate = new MyDataGridTemplate(ListItemType.Item, " 列1 " );
dg.Columns.Add(tc);
tc = new TemplateColumn();
tc.HeaderText = " 列2 " ;
tc.ItemTemplate = new MyDataGridTemplate(ListItemType.Item, " 列2 " );
dg.Columns.Add(tc);
tc = new TemplateColumn();
tc.HeaderText = " 列1 " ;
tc.ItemTemplate = new MyDataGridTemplate(ListItemType.Item, " 列1 " );
dg.Columns.Add(tc);
tc = new TemplateColumn();
tc.HeaderText = " 列2 " ;
tc.ItemTemplate = new MyDataGridTemplate(ListItemType.Item, " 列2 " );
dg.Columns.Add(tc);
以上代码的效果与下列代码相同:
<
asp:TemplateColumn
HeaderText
="列1"
>
< ItemTemplate >
< asp:Literal Runat ="server" Text ="列1" ></ asp:Literal >
</ ItemTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn HeaderText ="列2" >
< ItemTemplate >
< asp:Literal Runat ="server" Text ="列2" ></ asp:Literal >
</ ItemTemplate >
</ asp:TemplateColumn >
< ItemTemplate >
< asp:Literal Runat ="server" Text ="列1" ></ asp:Literal >
</ ItemTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn HeaderText ="列2" >
< ItemTemplate >
< asp:Literal Runat ="server" Text ="列2" ></ asp:Literal >
</ ItemTemplate >
</ asp:TemplateColumn >