TemplateField tf1 = new TemplateField();
tf1.ItemTemplate = ???
How to initialize this property?
If I need to this programmatically then what to do?
TemplateField tf1 = new TemplateField();
tf1.ItemTemplate = ???
How to initialize this property?
If I need to this programmatically then what to do?
You would usually do this sort of thing in the markup:
<TemplateField ...>
<ItemTemplate>
<asp:TextBox .../>
</ItemTemplate>
</TemplateField>
or do the same thing using the designer.
Example follows. The commented-out markup produces the same thing as the codebehind does:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
SelectCommand="SELECT Person.Contact.FirstName, Person.Contact.LastName
FROM Person.Contact
INNER JOIN HumanResources.Employee ON Person.Contact.ContactID = HumanResources.Employee.ContactID
WHERE (Person.Contact.LastName LIKE N'A%')
ORDER BY Person.Contact.LastName, Person.Contact.FirstName">
</asp:SqlDataSource>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<%-- <ItemTemplate>
<asp:Label runat="server" ID="lblLast">Name: </asp:Label>
<asp:Label runat="server" ID="lblName" Text='<%# DataBinder.Eval(Container.DataItem, "LastName")+", "+DataBinder.Eval(Container.DataItem, "FirstName") %>' />
</ItemTemplate>--%>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
</asp:Repeater>
</form>
</body>
</html>
Codebehind:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Repeater1.ItemTemplate = new TheItemTemplate();
}
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
}
public class TheItemTemplate : ITemplate
{
#region Implementation of ITemplate
public void InstantiateIn(Control container)
{
var lblLast = new Label {ID = "lblLast", Text = "Name: "};
container.Controls.Add(lblLast);
var lblName = new Label {ID = "lblName"};
lblName.DataBinding += delegate(object sender, EventArgs e)
{
var theLabel = (Label) sender;
var dataItem = DataBinder.GetDataItem(theLabel.BindingContainer);
theLabel.Text = DataBinder.Eval(dataItem, "LastName") + ", " +
DataBinder.Eval(dataItem, "FirstName");
};
container.Controls.Add(lblName);
}
#endregion
}
TemplateField tf1 = new TemplateField();
tf1.ItemTemplate = Page.LoadTemplate("ItemTemplate.ascx");