Binding columns dynamically in DataGrid

115527 Users read it.
by R.Arockia Jayaseelan (January 19, 2004)

Binding columns dynamically in DataGrid

 In this Article, you learn how to bind data in Bound column and Template column dynamically.

User Rating (66 votes)
2 reviews available | Read the reviews »
Author(s):R.Arockia Jayaseelan
User Level:Intermediate
Language:VB.NET
Platform:Web
Product(s):VS.NET, .NET Web Matrix

Binding columns dynamically in DataGrid

DataGrid one of the web server control, which displays data in tabular and read only format by default. Also capable of displaying editable controls automatically, during run time. Additionally it supports paging. Control must bind to a data source via its DataSource. By default DataGrid Control generates bound column for each field in the data source. When web page runs your code must call the control’s DataBind method to load the grid with data. In order to control the content and layout of the columns precisely, developer can define the following type of columns

BoundColumn.

Display textual fields. It renders as plain text but converts to a   TextBox when the Datagrid is placed into Edit mode.

HyperLinkColumn

Display text data. Which also represents a Web address (URL). The URL may or may not be the same as the display text; both can be set independently. It renders as an <a href=...> tag.

ButtonColumn

Allowing user interaction with the grid on a row basis. It can be rendered as either a hyperlinked LinkButton (<a href=...>), or a Pushbutton (<input type="button">). A PostBack is triggered when the button is clicked, and the ItemCommand event is fired on the Datagrid.

EditCommandColumn

This is similar to ButtonColumn, but it automatically creates buttons for editing the Datagrid, and for canceling or submitting the changes made. Fires the ItemCommand event, plus the specific event for the button clicked, EditCommand, CancelCommand, or UpdateCommand.

TemplateColumn

Full control over what controls are displayed to the user, divided into different templates, such as ItemTemplate and EditItemTemplate. Any ASP.NET or HTML control or set of controls can be placed inside those templates.

In this Article, you learn how to bind data in Bound column and Template column dynamically. Here I am using Icollection interface to hold my data.

Private Function CreateDataSource() As ICollection

        Dim dtExample As DataTable

        Dim drExample As DataRow

        Dim intI As Integer

 

        dtExample = New DataTable()

        '       First Coluumn

        dtExample.Columns.Add(New DataColumn("IntegerValue", GetType(Integer)))

        '       Second Column

        dtExample.Columns.Add(New DataColumn("StringValue", GetType(String)))

        '       Itrate, and create 6 rows

        For intI = 0 To 5

            drExample = dtExample.NewRow()

            drExample(0) = intI

            drExample(1) = "Row :" & intI.ToString()

            dtExample.Rows.Add(drExample)

        Next

        '       Add rows into Data view and return as Collection

        Return New DataView(dtExample)

    End Function

 

Boundcolumn

To visualize data grid, we need some container, hear I am using a Label control as container to hold my grid.

My aspx file contains 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

    <HEAD>

        <title>BindingData</title>

        <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">

        <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">

        <meta name="vs_defaultClientScript" content="JavaScript">

        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

    </HEAD>

    <body MS_POSITIONING="GridLayout">

        <form id="Form1" method="post" runat="server">

            <asp:label id="lblShowGrid" runat="server" />

        </form>

    </body>

</HTML>

And code behind file contains BoundColumn procedure

Private Sub BoundColumn()

        Dim DataGrid1 As New DataGrid()

        '       Binding Data Source

        DataGrid1.DataSource = CreateDataSource()

        DataGrid1.AutoGenerateColumns = False

 

        '       First column

        Dim bc1 As New BoundColumn()

        bc1.DataField = "IntegerValue"

        bc1.HeaderText = "Row ID"

        DataGrid1.Columns.Add(bc1)

        '       Second column

        Dim bc2 As New BoundColumn()

        bc2.DataField = "StringValue"

        bc2.HeaderText = "Row Value"

        '       Adding columns to grid

        DataGrid1.Columns.Add(bc2)

        '       Adding Datagrid to Label Control

        lblShowGrid.Controls.Add(DataGrid1)

        '       Binding

        DataGrid1.DataBind()

    End Sub

In your page load, just call Bound column procedure.

Templatecolumn

Using ITemplate interface you can bind Template column dynamically with the help of ITemplate interface and its method called “InstantiateIn”

First step declare Template Column in your code behind file.

Private TempCol As New TemplateColumn()

Now Create a New Template Class

 Public Class MyTemp

    Implements ITemplate

    Dim TemplateType As ListItemType

    Dim Field1 As String

    Dim Field2 As String

 

    Sub New(ByVal type As ListItemType, ByVal fld1 As String, ByVal fld2 As String)

        TemplateType = type

        Field1 = fld1

        Field2 = fld2

    End Sub

    Sub InstantiateIn(ByVal Container As Control) Implements ITemplate.InstantiateIn

        Dim lbl1 As Label = New Label()

        Dim lbl2 As Label = New Label()

        Dim lc1 As LiteralControl = New LiteralControl()

        Dim lc2 As LiteralControl = New LiteralControl()

        Select Case TemplateType

            Case ListItemType.Header

                lc1.ID = "lc1"

                lc1.Text = Field1

                Container.Controls.Add(lc1)

                lc2.ID = "lc2"

                lc2.Text = Field2

                Container.Controls.Add(lc2)

            Case ListItemType.Item

                lbl1.ID = "lbl1"

                AddHandler lbl1.DataBinding, AddressOf BindIntegerColumn

                Container.Controls.Add(lbl1)

                lbl2.ID = "lbl2"

                AddHandler lbl2.DataBinding, AddressOf BindStringColumn

                Container.Controls.Add(lbl2)

        End Select

    End Sub

    Sub BindIntegerColumn(ByVal Sender As Object, ByVal e As EventArgs)

        Dim lbl1 As Label = CType(Sender, Label)

        Dim Container As DataGridItem = CType(lbl1.NamingContainer, DataGridItem)

        lbl1.Text = DataBinder.Eval(Container.DataItem, Field1)

    End Sub

    Sub BindStringColumn(ByVal sender As Object, ByVal e As EventArgs)

        Dim lbl2 As Label = CType(sender, Label)

        Dim Container As DataGridItem = CType(lbl2.NamingContainer, DataGridItem)

        lbl2.Text = DataBinder.Eval(Container.DataItem, Field2)

    End Sub

   Add the following method in your code behind and call this procedure in your page load.    

Private Sub Template()

        Dim DataGrid1 As New DataGrid()

        DataGrid1.AutoGenerateColumns = False

        Dim Field1 As String

        Dim Field2 As String

        Dim Header1 As String

        Dim Header2 As String

        Field1 = "IntegerValue"

        Field2 = "StringValue"

        Header1 = "Row ID"

        Header2 = "Row Value"

        '       Header Template

        TempCol.HeaderTemplate = New MyTemp(ListItemType.Header, Header1, Header2)

        '       Item Template

        TempCol.ItemTemplate = New MyTemp(ListItemType.Item, Field1, Field2)

        '       Add Template into Grid

        DataGrid1.Columns.Add(TempCol)

        '       Binding Data Source

        DataGrid1.DataSource = CreateDataSource()

        DataGrid1.DataBind()

        '       Bind Grid into Label

        Me.lblShowGrid.Controls.Add(DataGrid1)

    End Sub

My Page Load look like

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Put user code to initialize the page here

        BoundColumn()

        Template()

    End Sub

 

R.Arockia Jayaseelan

R.Arockia Jayaseelan* Having 6+ Years of experience in Client Server and Web related Technologies.

* Working as a Software Engineer, USA.

See All Postings From R.Arockia Jayaseelan >>

User Reviews

Total of 2 reviews
Get data from dynamically controls created in template column
Written by Kathy Ferro on October 14, 2005

This article had help me. I'm creating controls base on the fields in the sql table. These fields are editable. It display the values the way I want it, but I'm having problem with reference the control. I assign the field name from the table ...

How to Count Sum on Footer
Written by Peter Wu on January 13, 2005

Hi, I had problem w/ sum of one column(Amount), my code is like, Protected amountSum AsDouble ... Case ListItemType.Footer If ColumnNo = 3 Then Dim lb2 AsNew Label AddHandler lb2.DataBinding, AddressOf BindColumn3 container.Controls.Add(lb2) ... ...

Follow us on twitter Subscribe to our RSS feed
Activate your free membership today | Login | Currency