New to Telerik UI for ASP.NET AJAXStart a free 30-day trial

Adding Templates at Run-time

You can also add templates to RadMenu 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 RadMenu items 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 RadMenu 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.

C#
protected override void OnInit(EventArgs e)
{    RadMenu1.ItemTemplate = new TextBoxTemplate();    
    base.OnInit(e);
}

protected void Page_Load(object sender, EventArgs e)
{    
    if (!Page.IsPostBack)
    {        
        RadMenu1.Items.Add(new RadMenuItem("MenuItem1"));
        RadMenu1.Items.Add(new RadMenuItem("MenuItem2"));
    }    
    RadMenu1.DataBind();
}

class TextBoxTemplate : ITemplate
{    
    public void InstantiateIn(Control container)    
    {        
        Label label1 = new Label();
        label1.ID = "ItemLabel";
        label1.Text = "Text";
        label1.Font.Size = 15;
        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;
        RadMenuItem item = (RadMenuItem)target.BindingContainer;
        string itemText = (string)DataBinder.Eval(item, "Text");
        target.Text = itemText;
    }
}	    			

If you for some reason cannot define the template in the OnInit event of the page, 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.

C#
protected void Page_Load(object sender, EventArgs e)
{    
    if (!Page.IsPostBack)    
    {        
        RadMenu1.Items.Add(new RadMenuItem("MenuItem1"));
        RadMenu1.Items.Add(new RadMenuItem("MenuItem2"));
    }        
    
    TextBoxTemplate template = new TextBoxTemplate();
    foreach (RadMenuItem item in RadMenu1.GetAllItems())
    {        
        template.InstantiateIn(item);
    }
    RadMenu1.DataBind();
}	    			

The end result of this code looks like the following:

RadMenu Dynamic Template

Not finding the help you need?
Contact Support