Live Chat Icon For mobile
Live Chat Icon

How to add a Templatecolumn dynamically to a DataList

Platform: ASP.NET| Category: DataList

<asp:DataList id='DataList1' runat='server'></asp:DataList>


In class

Public Class DatalistLabelColumn
    Implements ITemplate

Public Sub New()
End Sub ’New

Public Sub InstantiateIn(ByVal container As Control) Implements System.Web.UI.ITemplate.InstantiateIn
        	Dim label1 As New Label
        	AddHandler label1.DataBinding, AddressOf Me.BindLabelColumn
End Sub ’InstantiateIn

Public Sub BindLabelColumn(ByVal sender As Object, ByVal e As EventArgs)
        	Dim lbl As Label = CType(sender, Label)
        	Dim container As DataListItem = CType(lbl.NamingContainer, DataListItem)
        	Dim strVals As [String] = Convert.ToString(DataBinder.Eval(CType(container, DataListItem).DataItem, 'LastName')) + ', ' + Convert.ToString(DataBinder.Eval(CType(container, DataListItem).DataItem, 'FirstName'))
        	lbl.Text = strVals
End Sub ’BindLabelColumn 

End Class ’DatalistLabelColumn

Dim ds As DataSet = ’Fill the dataset
DataList1.ItemTemplate = New DatalistLabelColumn
DataList1.DataSource = ds


In class

public class DatalistLabelColumn : ITemplate
	public DatalistLabelColumn()
		//Add constructor stuff here

	public void InstantiateIn(Control container)
		Label label1 = new Label();
		label1.DataBinding += new EventHandler(this.BindLabelColumn);

	public void BindLabelColumn(object sender, EventArgs e)
		Label lbl = (Label)sender;
		DataListItem  container = (DataListItem)lbl.NamingContainer ;
		String strVals =Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, 'LastName')) 
			+ ', ' +
			Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, 'FirstName')) ;
		lbl.Text  = strVals;

DataSet ds = //Assign appropriate value;
DataList1.ItemTemplate = new DatalistLabelColumn();
DataList1.DataSource =ds;

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.