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

Editable Nested DataGrid

Rate me:
Please Sign up or sign in to vote.
4.81/5 (52 votes)
11 Mar 2007CPOL5 min read 411.9K   4.9K   191  
How to Create a Nested DataGrid in ASP.NET Using C#
' ---------------------------------------------------------
' Satya Kanithi's Editable Nested DataGrid
' ---------------------------------------------------------
'=======================================================
' FileName		    : WebForm1.aspx
' Description		: Multi Purpose DataGrid, Which can be expandable to many child grids 
' Date of Creation 	: Oct11, 2006
' Author		    : Satya Kanithi
'=======================================================
Imports System.Data.OleDb

Public Class WebForm1
    Inherits System.Web.UI.Page
    '--------------Control Declaration ----------
    Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
    Protected WithEvents DataGrid2 As System.Web.UI.WebControls.DataGrid
    Protected WithEvents lblMessage As System.Web.UI.WebControls.Label
    Protected WithEvents Literal1 As System.Web.UI.WebControls.Literal

#Region " Web Form Designer Generated Code "

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

    End Sub

    '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()
    End Sub

#End Region

#Region "Variables"
    Dim dgUniqueID As String
    Dim dgEditItemIndex As Int32
    Dim dgCurrentPageIndex As Int32
    Dim dgSortExpression As String
    Private Enum ExceptionType
        Red = 1
        Green = 2
        Yellow = 3
    End Enum    
#End Region

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

        '//Clear the Message if any
        lblMessage.Text = ""

        If Not Page.IsPostBack Then
            BindData()
            'Reset the session variables
            Session("CustomerID") = ""
            Session("PrevItemIndex") = -1
            dgSortExpression = ""
        End If
    End Sub

    '//This procedure binds the DataGrid with Query Details
    Private Sub BindData(Optional ByVal astrSort As String = "", Optional ByVal astrSort1 As String = "")

        Dim lstrSQL As String
        Dim ldtbParentTable As New DataTable
        Dim ldtbChildTable As New DataTable
        Dim ds As New DataSet
        Dim lobjDataRelation As DataRelation
        Dim lintPageSize As Int32
        Dim llngTotalRec As Int32
        Dim conn
        Dim dcCust
        Dim daCust
        Dim dcOrder
        Dim daOrder

        Try
            '//Prepare the connection object
            conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath(ConfigurationSettings.AppSettings("MDBPATH")))
            conn.open()

            'Query to get Customer Details - Parent Query
            lstrSQL = "SELECT [Customers].[CustomerID], [Customers].[CompanyName], " & _
                      "[Customers].[ContactName],[Customers].[ContactTitle], " & _
                      "[Customers].[Address] FROM [Customers] "

            '//Sort order provided
            If astrSort <> "" Then
                lstrSQL = lstrSQL & " ORDER BY " & astrSort
            Else
                'Default sort order
                lstrSQL = lstrSQL & " ORDER BY [CUSTOMERS].[CUSTOMERID] ASC"
            End If

            dcCust = New OleDbCommand(lstrSQL, conn)
            daCust = New OleDbDataAdapter(dcCust)
            daCust.Fill(ldtbParentTable)
            ldtbParentTable.TableName = "ParentTable"

            'Query to get Order Details - Child Query
            lstrSQL = "SELECT [Orders].[CustomerID] as ChildCustomerID,[Orders].[OrderID],[Orders].[ShipAddress]," & _
                      "[Orders].[Freight],[Orders].[ShipName] FROM [Orders]"

            '//Sort order provided
            If astrSort1 <> "" Then
                lstrSQL = lstrSQL & " ORDER BY " & astrSort1
            Else
                'Default sort order
                lstrSQL = lstrSQL & " ORDER BY [Orders].[OrderID] ASC"
            End If

            dcOrder = New OleDbCommand(lstrSQL, conn)
            daOrder = New OleDbDataAdapter(dcOrder)
            daOrder.Fill(ldtbChildTable)
            ldtbChildTable.TableName = "ChildTable"

            'Add both these tables to the dataset
            ds.Tables.Add(ldtbParentTable)
            ds.Tables.Add(ldtbChildTable)

            '//Create relation and this relation name should be used on CreateChildView
            Dim dr As New DataRelation("ParentTable_ChildTable", ldtbParentTable.Columns("CustomerID"), ldtbChildTable.Columns("ChildCustomerID"), False)
            dr.Nested = True
            ds.Relations.Add(dr)

            'Set the datasource to parent datagrid
            DataGrid1.DataSource = ds
            DataGrid1.DataBind()

        Catch exc As Exception
            LogMessage(exc)
            Exit Sub
        Finally
            daCust.Dispose()
            dcCust.Dispose()
            daOrder.Dispose()
            dcOrder.Dispose()
            ds.Dispose()
            conn.close()
        End Try
    End Sub

    '//Log messages
    Sub LogMessage(ByVal exc As Exception, Optional ByVal param As Int32 = ExceptionType.Red)
        If param = ExceptionType.Red Then
            lblMessage.Text = exc.Message.ToString().Substring(0, exc.Message.Length - 1)
            lblMessage.ForeColor = System.Drawing.Color.Red
        ElseIf param = ExceptionType.Green Then
            lblMessage.Text = exc.Message
            lblMessage.ForeColor = System.Drawing.Color.Green
        ElseIf param = ExceptionType.Yellow Then
            lblMessage.Text = exc.Message
            lblMessage.ForeColor = System.Drawing.Color.Yellow
        End If
    End Sub

#Region "DataGrid1 Event handlers"
    '//This procedure handles the Parent Grid command events
    Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.ItemCommand

        Dim strSQL As String

        Select Case e.CommandName

            Case "Expand"               '//Case for expanding the + sign on Parent grid to show the child grid

                Dim img As ImageButton
                Dim exp As PlaceHolder

                'Before expanding, collapse previously opened child grid
                Dim dgItem As DataGridItem
                For Each dgItem In DataGrid1.Items
                    If dgItem.ItemIndex = Session("PrevItemIndex") And dgItem.ItemIndex <> e.Item.ItemIndex Then
                        img = dgItem.Cells(0).FindControl("ImageButton1")
                        If img.ImageUrl = "~/Images/Minus.gif" Then
                            img.ImageUrl = "~/Images/Plus.gif"
                            exp = dgItem.Cells(2).FindControl("Expanded")
                            exp.Visible = Not exp.Visible
                        End If
                        Exit For
                    End If
                Next

                img = e.Item.Cells(0).FindControl("ImageButton1")
                If img.ImageUrl = "~/Images/Plus.gif" Then
                    img.ImageUrl = "~/Images/Minus.gif"
                Else
                    img.ImageUrl = "~/Images/Plus.gif"
                End If

                exp = e.Item.Cells(2).FindControl("Expanded")
                exp.Visible = Not exp.Visible
                Session("PrevItemIndex") = e.Item.ItemIndex     'Store the ItemIndex in session variable
                Session("CustomerID") = e.Item.Cells(1).Text    'Store the CustomerID

            Case "Insert"   '//Case statement for Insert Click on Parent Grid
                Dim txtCustomerID As TextBox
                Dim txtCompanyName As TextBox
                Dim txtContactName As TextBox
                Dim txtContactTitle As TextBox
                Dim txtAddress As TextBox
                Dim lstrCustomerID As String
                Dim lstrCompanyName As String
                Dim lstrContactName As String
                Dim lstrContactTitle As String
                Dim lstrRFC As String
                Dim lstrAddress As String

                'Read in the values of the TextBoxes
                txtCustomerID = e.Item.FindControl("add_CustomerID")
                lstrCustomerID = txtCustomerID.Text.ToUpper
                txtCompanyName = e.Item.FindControl("add_CompanyName")
                lstrCompanyName = txtCompanyName.Text
                txtContactName = e.Item.FindControl("add_ContactName")
                lstrContactName = txtContactName.Text
                txtContactTitle = e.Item.FindControl("add_ContactTitle")
                lstrContactTitle = txtContactTitle.Text
                txtAddress = e.Item.FindControl("add_Address")
                lstrAddress = txtAddress.Text

                Dim conn
                Dim dcCust

                Try
                    'Check whether the record exists before adding...
                    strSQL = "SELECT COUNT(*) FROM [Customers] WHERE [Customers].[CustomerID] = '" & lstrCustomerID & "'"
                    conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath(ConfigurationSettings.AppSettings("MDBPATH")))
                    dcCust = New OleDbCommand(strSQL, conn)
                    conn.Open()
                    Dim count = dcCust.ExecuteScalar
                    If (count > 0) Then
                        Throw New Exception("Record already exists...")
                    End If
                    dcCust.Dispose()

                    'Create the SQL statement for addition
                    strSQL = "INSERT INTO Customers (CustomerID, CompanyName, ContactName, " & _
                    "ContactTitle, Address) VALUES ('" & lstrCustomerID & "','" & lstrCompanyName & "','" & _
                    lstrContactName & "','" & lstrContactTitle & "','" & lstrAddress & "')"

                    dcCust = New OleDbCommand(strSQL, conn)
                    dcCust.ExecuteNonQuery()
                    LogMessage(New Exception("Record added successfully..."), ExceptionType.Green)

                Catch exc As Exception
                    LogMessage(exc)
                    Exit Sub
                Finally
                    dcCust.Dispose()
                    conn.Close()
                End Try

                'Rebind the DataGrid                    
                BindData()

            Case "Edit" '//Edit Case
                DataGrid1.ShowFooter = False    'Hide the footer while editing
                DataGrid1.EditItemIndex = e.Item.ItemIndex
                BindData()

            Case "Cancel"   '//Cancel Case
                Try
                    DataGrid1.ShowFooter = True
                    DataGrid1.EditItemIndex = -1
                    BindData()
                Catch exc As Exception
                    LogMessage(exc)
                    Exit Sub
                End Try

            Case "Delete"   '//Delete Case

                Dim lstrCustomerID As String
                Dim conn
                Dim dcCust
                '//Get the Customer ID which is hidden bound column
                lstrCustomerID = e.Item.Cells(1).Text.ToUpper

                Try
                    'Check whether the records exists in child table before deleting...
                    strSQL = "SELECT COUNT(*) FROM [Orders] WHERE [Orders].[CustomerID] = '" & lstrCustomerID & "'"
                    conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath(ConfigurationSettings.AppSettings("MDBPATH")))
                    dcCust = New OleDbCommand(strSQL, conn)
                    conn.Open()
                    Dim count = dcCust.ExecuteScalar
                    If (count > 0) Then
                        Throw New Exception("Child records exists...")
                    End If
                    dcCust.Dispose()

                    'Create the SQL statement for addition
                    strSQL = "DELETE FROM Customers WHERE CustomerID = '" & lstrCustomerID & "'"

                    dcCust = New OleDbCommand(strSQL, conn)
                    dcCust.ExecuteNonQuery()
                    LogMessage(New Exception("Record deleted successfully..."), ExceptionType.Green)

                Catch exc As Exception
                    LogMessage(exc)
                    Exit Sub
                Finally
                    dcCust.Dispose()
                    conn.Close()
                End Try

                'Rebind the DataGrid
                BindData()

            Case "Update"   '//Update Case
                Dim txtCustomerID As TextBox
                Dim txtCompanyName As TextBox
                Dim txtContactName As TextBox
                Dim txtContactTitle As TextBox
                Dim txtAddress As TextBox
                Dim lstrCustomerID As String
                Dim lstrCompanyName As String
                Dim lstrContactName As String
                Dim lstrContactTitle As String
                Dim lstrRFC As String
                Dim lstrAddress As String

                'Read in the values of the TextBoxes                
                txtCustomerID = e.Item.FindControl("edit_CustomerID")   '//Customer ID will be in readonly format
                lstrCustomerID = txtCustomerID.Text.ToUpper
                txtCompanyName = e.Item.FindControl("edit_CompanyName")
                lstrCompanyName = txtCompanyName.Text
                txtContactName = e.Item.FindControl("edit_ContactName")
                lstrContactName = txtContactName.Text
                txtContactTitle = e.Item.FindControl("edit_ContactTitle")
                lstrContactTitle = txtContactTitle.Text
                txtAddress = e.Item.FindControl("edit_Address")
                lstrAddress = txtAddress.Text

                Dim conn
                Dim dcCust
                Try
                    'Create the SQL statement for updation
                    strSQL = "UPDATE Customers set CompanyName = '" & lstrCompanyName & "'"
                    strSQL = strSQL & ",ContactName = '" & lstrContactName & "'"
                    strSQL = strSQL & ",ContactTitle = '" & lstrContactTitle & "'"
                    strSQL = strSQL & ",Address = '" & lstrAddress & "'"
                    strSQL = strSQL & " WHERE CustomerID = '" & lstrCustomerID & "'"
                    conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath(ConfigurationSettings.AppSettings("MDBPATH")))
                    dcCust = New OleDbCommand(strSQL, conn)
                    conn.Open()
                    dcCust.ExecuteNonQuery()
                    LogMessage(New Exception("Record updated successfully..."), ExceptionType.Green)
                Catch exc As Exception
                    LogMessage(exc)
                    Exit Sub
                Finally
                    dcCust.Dispose()
                    conn.Close()
                End Try

                'Rebind the DataGrid
                DataGrid1.EditItemIndex = -1
                BindData()
        End Select
    End Sub

    '//This procedure is used for the purpose of edit on child grid
    '//When your program uses the DataGrid control, 
    '//and your program has a child DataGrid control that is associated with each row of a parent DataGrid control, 
    '//a problem may occur. When you click Edit for the child DataGrid control, nothing happens.
    '//This is known Microsoft Problem, I have used the resolution provided by Microsoft here
    '//Refer http://support.microsoft.com/default.aspx?scid=kb;en-us;815004 for more details
    Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound

        Dim dgTemp As New DataGrid        

        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
            dgTemp = CType(e.Item.FindControl("DataGrid2"), DataGrid)
            If dgTemp.UniqueID = dgUniqueID Then
                dgTemp.EditItemIndex = dgEditItemIndex

                'If the Edit Item Index is -1, On Cancel click
                If (dgEditItemIndex = -1) Then
                    dgTemp.ShowFooter = True
                Else
                    dgTemp.ShowFooter = False
                End If

                'Set the Page Index for child datagrid
                dgTemp.CurrentPageIndex = dgCurrentPageIndex

                '//Call the procedure to alter the Current Sort Expression
                alterSortExpression(dgTemp)

                '//Following code is for displaying back child grid after handling its button events
                Dim img As ImageButton
                img = e.Item.Cells(0).FindControl("ImageButton1")
                img.ImageUrl = "~/Images/Minus.gif"
                Dim exp As PlaceHolder
                exp = e.Item.Cells(2).FindControl("Expanded")
                exp.Visible = True

                dgTemp.DataBind()                

                dgUniqueID = ""
                dgEditItemIndex = -1

            End If
        End If

    End Sub

    '//Procedure for Parent DataGrid paging
    Private Sub DataGrid1_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DataGrid1.PageIndexChanged
        DataGrid1.CurrentPageIndex = e.NewPageIndex
        BindData()
    End Sub

    '//Procedure for Parent DataGrid Sorting
    Private Sub DataGrid1_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles DataGrid1.SortCommand

        Dim SortExprs() As String
        Dim CurrentSearchMode As String, NewSearchMode As String
        Dim ColumnToSort As String, NewSortExpr As String

        '  Parse the sort expression - delimiter space
        SortExprs = Split(e.SortExpression, " ")
        ColumnToSort = SortExprs(0)

        ' If a sort order is specified get it, else default is Ascending
        If SortExprs.Length() > 1 Then
            CurrentSearchMode = SortExprs(1).ToUpper()
            If CurrentSearchMode = "ASC" Then
                NewSearchMode = "DESC"
            Else
                NewSearchMode = "ASC"
            End If
        Else   ' If no mode specified, Default is descending
            NewSearchMode = "DESC"
        End If

        '  Derive the new sort expression. 
        NewSortExpr = ColumnToSort & " " & NewSearchMode

        ' Figure out the column index 
        Dim iIndex As Integer
        Select Case ColumnToSort.ToUpper()
            Case "[CUSTOMERS].[CUSTOMERID]"
                iIndex = 2
            Case "[CUSTOMERS].[COMPANYNAME]"
                iIndex = 3
            Case "[CUSTOMERS].[CONTACTNAME]"
                iIndex = 4
        End Select

        ' alter the column's sort expression 
        DataGrid1.Columns(iIndex).SortExpression = NewSortExpr

        'Reset the Page Number to start
        DataGrid1.CurrentPageIndex = 0

        ' Sort the data in new order
        BindData(NewSortExpr)
    End Sub

#End Region

#Region "DataGrid2 Event handlers"

    '//This procedure handles the Child Grid command events
    '//On runtime child grid will have different UniqueID, E.G DataGrid_Ctl1, So we must use source object for DataGrid specific events
    Public Sub DataGrid2_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)

        Dim strSQL As String
        Select Case e.CommandName

            Case "Insert"

                Dim txtFreight As TextBox
                Dim txtShipName As TextBox
                Dim txtShipAddress As TextBox
                Dim lstrCustomerID As String
                Dim ldblFreight As Double
                Dim lstrShipName As String
                Dim lstrShipAddress As String

                '//Here the Session variable being used was stored when the Parenrt grid '+' clicked
                lstrCustomerID = Session("CustomerID")

                'Read in the values of the TextBoxes                
                txtFreight = e.Item.FindControl("add_Freight")
                ldblFreight = CDbl(txtFreight.Text)
                txtShipName = e.Item.FindControl("add_ShipName")
                lstrShipName = txtShipName.Text
                txtShipAddress = e.Item.FindControl("add_ShipAddress")
                lstrShipAddress = txtShipAddress.Text

                Dim conn
                Dim dcOrder

                Try
                    conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath(ConfigurationSettings.AppSettings("MDBPATH")))

                    'Create the SQL statement for addition
                    strSQL = "INSERT INTO Orders (CustomerID, Freight, ShipName, " & _
                    "ShipAddress) VALUES ('" & lstrCustomerID & "'," & ldblFreight & ",'" & _
                    lstrShipName & "','" & lstrShipAddress & "')"

                    dcOrder = New OleDbCommand(strSQL, conn)
                    conn.Open()
                    dcOrder.ExecuteNonQuery()
                    LogMessage(New Exception("Record added successfully..."), ExceptionType.Green)

                    Dim dgTemp As New DataGrid
                    dgTemp = CType(source, DataGrid)
                    dgUniqueID = dgTemp.UniqueID
                    dgEditItemIndex = -1
                    '//Set the current PageIndex
                    dgCurrentPageIndex = 0
                Catch exc As Exception
                    LogMessage(exc)
                    Exit Sub
                Finally
                    dcOrder.Dispose()
                    conn.Close()
                End Try

                'Rebind the DataGrid                    
                BindData()

            Case "Edit"
                Try
                    'Cast dgTemp to incoming DataGrid
                    Dim dgTemp As New DataGrid
                    dgTemp = CType(source, DataGrid)
                    '//Getting the UniqueID of the child datagrid using the source object
                    dgUniqueID = dgTemp.UniqueID
                    '//Store the EditItemIndex to be used later in DataGrid1_ItemDataBound procedure
                    dgEditItemIndex = e.Item.ItemIndex
                    '//Store the current PageIndex
                    dgCurrentPageIndex = dgTemp.CurrentPageIndex
                    BindData()
                Catch exc As Exception
                    LogMessage(exc)
                    Exit Sub
                End Try

            Case "Cancel"
                Try
                    'Cast dgTemp to incoming DataGrid
                    Dim dgTemp As New DataGrid
                    dgTemp = CType(source, DataGrid)
                    dgUniqueID = dgTemp.UniqueID
                    dgEditItemIndex = -1
                    '//Store the current PageIndex
                    dgCurrentPageIndex = dgTemp.CurrentPageIndex
                    BindData()
                Catch exc As Exception
                    LogMessage(exc)
                    Exit Sub
                End Try

            Case "Update"

                Dim txtOrderID As TextBox
                Dim txtFreight As TextBox
                Dim txtShipName As TextBox
                Dim txtShipAddress As TextBox
                Dim ldblFreight As Double
                Dim lstrShipName As String
                Dim lstrShipAddress As String
                Dim lintOrderID As Int64

                'Read in the values of the TextBoxes 
                txtOrderID = e.Item.FindControl("edit_OrderID")
                lintOrderID = CInt(txtOrderID.Text) '//Order ID will be in Readonly format
                txtFreight = e.Item.FindControl("edit_Freight")
                ldblFreight = CDbl(txtFreight.Text)
                txtShipName = e.Item.FindControl("edit_ShipName")
                lstrShipName = txtShipName.Text
                txtShipAddress = e.Item.FindControl("edit_ShipAddress")
                lstrShipAddress = txtShipAddress.Text

                Dim conn
                Dim dcOrder

                Try
                    conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath(ConfigurationSettings.AppSettings("MDBPATH")))

                    'Create the SQL statement for updation
                    strSQL = "UPDATE Orders set Freight = " & ldblFreight
                    strSQL = strSQL & ",ShipName = '" & lstrShipName & "'"
                    strSQL = strSQL & ",ShipAddress = '" & lstrShipAddress & "'"
                    strSQL = strSQL & " WHERE OrderID = " & lintOrderID

                    dcOrder = New OleDbCommand(strSQL, conn)
                    conn.Open()
                    dcOrder.ExecuteNonQuery()
                    LogMessage(New Exception("Record updated successfully..."), ExceptionType.Green)

                    'Cast dgTemp to incoming DataGrid
                    Dim dgTemp As New DataGrid
                    dgTemp = CType(source, DataGrid)
                    dgUniqueID = dgTemp.UniqueID
                    dgEditItemIndex = -1
                    '//Store the current PageIndex                    
                    dgCurrentPageIndex = dgTemp.CurrentPageIndex
                Catch exc As Exception
                    LogMessage(exc)
                    Exit Sub
                Finally
                    dcOrder.Dispose()
                    conn.Close()
                End Try

                'Rebind the DataGrid                    
                BindData()

            Case "Delete"

                Dim ldblOrderID As Int64

                'Read in the BoundColumn value of the hidden Order ID value                                
                ldblOrderID = CInt(e.Item.Cells(0).Text)

                Dim conn
                Dim dcOrder

                Try
                    conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Server.MapPath(ConfigurationSettings.AppSettings("MDBPATH")))

                    'Create the SQL statement for addition
                    strSQL = "DELETE FROM Orders WHERE OrderID = " & ldblOrderID

                    dcOrder = New OleDbCommand(strSQL, conn)
                    conn.Open()
                    dcOrder.ExecuteNonQuery()
                    LogMessage(New Exception("Record deleted successfully..."), ExceptionType.Green)

                    'Cast dgTemp to incoming DataGrid
                    Dim dgTemp As New DataGrid
                    dgTemp = CType(source, DataGrid)
                    dgUniqueID = dgTemp.UniqueID
                    dgEditItemIndex = -1
                    '//Set the current PageIndex                    
                    dgCurrentPageIndex = 0
                Catch exc As Exception
                    LogMessage(exc)
                    Exit Sub
                Finally
                    dcOrder.Dispose()
                    conn.Close()
                End Try

                'Rebind the DataGrid                    
                BindData()
        End Select
    End Sub

    '//Procedure for Child DataGrid paging
    Public Sub DataGrid2_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs)
        dgCurrentPageIndex = e.NewPageIndex
        'Cast dgTemp to incoming DataGrid
        Dim dgTemp As New DataGrid
        dgTemp = CType(source, DataGrid)
        '//Getting the UniqueID of the child datagrid using the source object
        dgUniqueID = dgTemp.UniqueID
        '//Store the EditItemIndex to be used later in DataGrid1_ItemDataBound procedure
        dgEditItemIndex = -1
        BindData()
    End Sub

    '//Procedure for Child DataGrid Sorting
    Public Sub DataGrid2_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)

        '//Store the Sort expression, to be used later
        dgSortExpression = e.SortExpression

        'Cast dgTemp to incoming DataGrid
        Dim dgTemp As New DataGrid
        dgTemp = CType(source, DataGrid)
        '//Getting the UniqueID of the child datagrid using the source object
        dgUniqueID = dgTemp.UniqueID
        '//Store the EditItemIndex to be used later in DataGrid1_ItemDataBound procedure
        dgEditItemIndex = -1
        dgCurrentPageIndex = 0

        '//Get the Sort Expression to sort the child grid
        Dim SortExpr As String
        SortExpr = getSortExpression(dgTemp)
        BindData(, SortExpr)

    End Sub

    '//This function returns the new sort expression to sort the child DataGrid
    Private Function getSortExpression(ByVal dgTemp As DataGrid) As String
        Dim SortExprs() As String
        Dim CurrentSearchMode As String, NewSearchMode As String
        Dim ColumnToSort As String, NewSortExpr As String

        '  Parse the sort expression - delimiter space
        SortExprs = Split(dgSortExpression, " ")
        ColumnToSort = SortExprs(0)

        ' If a sort order is specified get it, else default is Ascending
        If SortExprs.Length() > 1 Then
            CurrentSearchMode = SortExprs(1).ToUpper()
            If CurrentSearchMode = "ASC" Then
                NewSearchMode = "DESC"
            Else
                NewSearchMode = "ASC"
            End If
        Else   ' If no mode specified, Default is descending
            NewSearchMode = "DESC"
        End If

        '  Derive the new sort expression. 
        NewSortExpr = ColumnToSort & " " & NewSearchMode

        Return NewSortExpr

    End Function

    '//This function alters the child datagrid sort expression
    Private Sub alterSortExpression(ByVal dgTemp As DataGrid)
        Dim SortExprs() As String
        Dim ColumnToSort As String, NewSortExpr As String

        '  Parse the sort expression - delimiter space
        SortExprs = Split(dgSortExpression, " ")
        ColumnToSort = SortExprs(0)

        ' Figure out the column index 
        Dim iIndex As Integer
        Select Case ColumnToSort.ToUpper()
            Case "[ORDERS].[ORDERID]"
                iIndex = 1
            Case "[ORDERS].[FREIGHT]"
                iIndex = 2
            Case "[ORDERS].[SHIPNAME]"
                iIndex = 3
        End Select

        ' alter the column's sort expression 
        dgTemp.Columns(iIndex).SortExpression = getSortExpression(dgTemp)

    End Sub

#End Region

    
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
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