Live Chat Icon For mobile
Live Chat Icon

How to add a TemplateColumn dynamically to the datagrid

Platform: ASP.NET| Category: DataGrid

<asp:DataGrid id='DataGrid1' AutoGenerateColumns=False  runat='server'></asp:DataGrid>


Create class

Public Class newLabelColumn
    Implements ITemplate

Public Sub New()
End Sub ’New

’Add constructor stuff here
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 DataGridItem = CType(lbl.NamingContainer, DataGridItem)
        	Dim strVals As [String] = Convert.ToString(DataBinder.Eval(CType(container, DataGridItem).DataItem, 'LastName')) + ', ' + Convert.ToString(DataBinder.Eval(CType(container, DataGridItem).DataItem, 'FirstName'))
        	lbl.Text = strVals
End Sub ’BindLabelColumn
End Class ’newLabelColumn

’Fill the Dataset
Dim objtc As New TemplateColumn
objtc.HeaderText = 'Full Name'
objtc.ItemTemplate = New newLabelColumn
DataGrid1.DataSource = ds


Create class

public class newLabelColumn : ITemplate
	public newLabelColumn()
		//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;
		DataGridItem container = (DataGridItem)lbl.NamingContainer ;
		String strVals 	=
		Convert.ToString(DataBinder.Eval(((DataGridItem)container).DataItem, 	'LastName')) + ', '
		Convert.ToString(DataBinder.Eval(((DataGridItem)container).DataItem, 'FirstName')) ;
		lbl.Text = strVals;

//Fill the DataSet
TemplateColumn objtc = new TemplateColumn();
objtc.HeaderText = 'Full Name';
objtc.ItemTemplate = new newLabelColumn();
DataGrid1.DataSource =ds;

Share with

Related FAQs

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

Please submit your question and answer.