ServerTemplates
You can also add Templates to RadDropDownList at runtime, using the ItemTemplate property. This property is of type ITemplate, so you must assign an object that implements that interface as a value:
The DropDownListItems should be dynamically added so that Templates can be defined at run time. Also, the Items should be bound to be able to eval DataBinder expressions. In other words, you should call the DataBind method of the RadDropDownList object or bind the Items that are about to use DataBinder.Eval . You can bind a specific item by calling the DataBind method of this specific Item.
The ItemTemplate should be initialized in the OnInit event of the page. This is needed as the Template should be instantiated before the DropDownListItems are initialized.
protected override void OnInit(EventArgs e)
{
RadDropDownList1.ItemTemplate = new TextBoxTemplate();
base.OnInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RadDropDownList1.Items.Add(new DropDownListItem("Item1")); RadDropDownList1.Items.Add(new DropDownListItem("Item2"));
}
RadDropDownList1.DataBind();
}
class TextBoxTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
Label label1 = new Label();
label1.ID = "ItemLabel";
label1.Text = "Text";
label1.Font.Size = 10;
label1.Font.Bold = true;
label1.DataBinding += new EventHandler(label1_DataBinding);
container.Controls.Add(label1);
}
private void label1_DataBinding(object sender, EventArgs e)
{
Label target = (Label)sender;
DropDownListItem node = (DropDownListItem)target.BindingContainer;
string nodeText = (string)DataBinder.Eval(node, "Text");
target.Text = nodeText;
}
}
If you want to add different templates to specific items, based on some property or value for instance, the best way is to use the TemplateNeeded event.
protected void RadDropDownList1_TemplateNeeded1(object sender, DropDownListItemEventArgs e)
{
var textBoxTemplate = new TextBoxTemplate();
RadDropDownList1.ItemTemplate = textBoxTemplate;
}
If for some reason you cannot define the Template in the OnInit event of the page, or take advantage of the TemplateNeeded event, you could use another approach:
The Template has to be instantiated for each Item upon a postback. Since the TextBoxTemplate class initializes the Label on InstantiateIn we called the InstantiateIn method of the TextBoxTemplate object for each Item.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RadDropDownList1.Items.Add(new DropDownListItem("Item1")); RadDropDownList1.Items.Add(new DropDownListItem("Item2"));
}
TextBoxTemplate template = new TextBoxTemplate();
foreach (DropDownListItem item in RadDropDownList1.Items)
{
template.InstantiateIn(item);
}
RadDropDownList1.DataBind();
}