Click here to Skip to main content
15,885,216 members
Articles / Web Development / ASP.NET

Dynamically load controls into a DataGrid

Rate me:
Please Sign up or sign in to vote.
4.14/5 (21 votes)
21 Sep 20043 min read 157.5K   2.4K   72  
A method for loading a DataGrid with controls at runtime, and later allowing DataSet updates.
Public Class DynamicControls
    Inherits System.Web.UI.Page


#Region " Web Form Designer Generated Code "

        'This call is required by the Web Form Designer.
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

        End Sub
        Protected WithEvents dg1 As System.Web.UI.WebControls.DataGrid
        Protected WithEvents cmdUpdate As System.Web.UI.WebControls.Button

        'NOTE: The following placeholder declaration is required by the Web Form Designer.
        'Do not delete or move it.
        Private designerPlaceholderDeclaration As System.Object

        Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
            'CODEGEN: This method call is required by the Web Form Designer
            'Do not modify it using the code editor.
            InitializeComponent()
            ' MakeDatafiles()

        End Sub

#End Region
    'This code example dynamically loads a datagrid with a variety of controls 
    'and allows controls to be rebound
    'the original data source
    Private strFileLoc As String = "c:\inetpub\wwwroot\samplegrid\AboutMe.xml"
        Public myDS As New DataSet

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Create the data file once
        If Not System.IO.File.Exists(strFileLoc) Then
            MakeSampleDatafiles()
        End If
        'on every page load, load data from XML file
        LoadDataset()
    End Sub
    Private Sub LoadDataset()
        myDS.ReadXml(strFileLoc)
        dg1.DataSource = myDS
        dg1.DataMember = "myDetails"
        DataBind()
    End Sub


    Private Sub MakeSampleDatafiles()
        'Create sample data for this example
        Dim myDS As New DataSet

        Dim myDataTable As New DataTable("myDetails")

        myDataTable.Columns.Add("name", GetType(String))
        myDataTable.Columns.Add("value", GetType(String))
        myDataTable.Columns.Add("type", GetType(String))
        myDataTable.Columns.Add("populate", GetType(String))

        Dim r As DataRow
        r = myDataTable.NewRow
        r(0) = "Name"
        r(1) = "Mark"
        r(2) = "txtbox"
        myDataTable.Rows.Add(r)

        r = myDataTable.NewRow
        r(0) = "Car"
        r(1) = "4"
        r(2) = "ddl"
        r(3) = "CarMake"
        myDataTable.Rows.Add(r)

        r = myDataTable.NewRow
        r(0) = "Licensed?"
        r(1) = "T"
        r(2) = "checkbox"
        myDataTable.Rows.Add(r)

        r = myDataTable.NewRow
        r(0) = "Brother"
        r(1) = "Jeff"
        r(2) = "txtbox"
        myDataTable.Rows.Add(r)

        myDS.Tables.Add(myDataTable)

        Dim myDataTable2 As New DataTable("CarMake")

        myDataTable2.Columns.Add("carmake", GetType(String))

        r = myDataTable2.NewRow
        r(0) = "Ford"
        myDataTable2.Rows.Add(r)

        r = myDataTable2.NewRow
        r(0) = "Holden"
        myDataTable2.Rows.Add(r)

        r = myDataTable2.NewRow
        r(0) = "Mercedes"
        myDataTable2.Rows.Add(r)

        r = myDataTable2.NewRow
        r(0) = "Mitsubishi"
        myDataTable2.Rows.Add(r)

        r = myDataTable2.NewRow
        r(0) = "Nissan"
        myDataTable2.Rows.Add(r)

        myDS.Tables.Add(myDataTable2)

        myDS.WriteXml(strFileLoc)


    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
        'in this example the button does no work!
    End Sub

    Private Sub dg1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dg1.ItemDataBound
        'the ItemDataBound event is raise for every row in the datasource
        If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
            'This example loads a label in cell 0 with the data name
            Dim myLBL As New Label
            myLBL.EnableViewState = True

            myLBL.Text = dgTable(dg1).Rows(e.Item.DataSetIndex)(0)
            e.Item.Cells(0).Controls.Add(myLBL)
            If dgTable(dg1).Rows(e.Item.DataSetIndex)(2) = "txtbox" Then
                'craete and load a textbox
                Dim myTB As New TextBox
                If Not IsPostBack Then
                    myTB.Text = dgTable(dg1).Rows(e.Item.DataSetIndex)(1)
                End If
                e.Item.Cells(1).Controls.Add(myTB)
            ElseIf dgTable(dg1).Rows(e.Item.DataSetIndex)(2) = "checkbox" Then
                'create and load a checkbox
                Dim myCB As New CheckBox
                If Not IsPostBack Then
                    If dgTable(dg1).Rows(e.Item.DataSetIndex)(1).tolower = "t" Then
                        myCB.Checked = True
                    Else
                        myCB.Checked = False
                    End If
                End If
                e.Item.Cells(1).Controls.Add(myCB)
            ElseIf dgTable(dg1).Rows(e.Item.DataSetIndex)(2) = "ddl" Then
                'create and load a dropdownlist
                Dim myDDL As New DropDownList
                For yy As Int16 = 0 To dg1.DataSource.Tables("CarMake").Rows.Count - 1
                    myDDL.Items.Add(dg1.DataSource.Tables("CarMake").Rows(yy)(0))
                Next
                e.Item.Cells(1).Controls.Add(myDDL)

                If Not IsPostBack Then
                    myDDL.SelectedIndex = CType(dgTable(dg1).Rows(e.Item.DataSetIndex)(1), Int16)
                End If
            End If
        End If
    End Sub
    Private Function dgTable(ByVal dg As DataGrid) As DataTable
        'return the table bound to the datagrid
        Return dg1.DataSource.tables(dg1.DataMember)
    End Function


    Private Sub dg1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles dg1.PreRender
        ' this is where the dataset update actually happens!!
        Dim y As Int16
        'run through each line in the datagrid
        For y = 0 To dgTable(dg1).Rows.Count - 1
            'repopulate the dataset with content based on the embedded control
            If dg1.Items(y).Cells(1).Controls(0).GetType Is GetType(DropDownList) Then
                Dim myIndex As Int32 = CType(dg1.Items(y).Cells(1).Controls(0), DropDownList).SelectedIndex
                dgTable(dg1).Rows(y)(1) = myIndex.ToString
            End If
            If dg1.Items(y).Cells(1).Controls(0).GetType Is GetType(TextBox) Then
                Dim myStr As String = CType(dg1.Items(y).Cells(1).Controls(0), TextBox).Text
                dgTable(dg1).Rows(y)(1) = myStr
            End If
            If dg1.Items(y).Cells(1).Controls(0).GetType Is GetType(CheckBox) Then
                If CType(dg1.Items(y).Cells(1).Controls(0), CheckBox).Checked = True Then
                    dgTable(dg1).Rows(y)(1) = "T"
                Else
                    dgTable(dg1).Rows(y)(1) = "F"
                End If
            End If
        Next
        dg1.DataSource.WriteXml(strFileLoc)
    End Sub
End Class



By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions