Help-How to sort columns in a table web control that's generated dynamically in code behind page?

Posted on 2004-11-11
Last Modified: 2012-08-13

I am using table web control in code behind to generate a result table.  When a button clicked, it'll display the result.  Now I need to place sorting on each column.  I tried to declare a link button event and added event handler for the click event.  But it didn't work.  

Can anybody tell me how to add a sort function?

Thank you.


***** =============================================================********
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Public Class test
    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 btnDisplay As System.Web.UI.WebControls.Button
    Protected WithEvents tblResult As System.Web.UI.WebControls.Table
    protected withEvents b as system.web.ui.webcontrols.linkbutton
***** =============================================================********
    '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.
    End Sub

#End Region

    Protected sortorder As String = ""

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'to add event handler on page load
        addhandler, addressof sorttotal_click

        If Not Page.IsPostBack Then
        End If
    End Sub 'Page_Load

    Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
        'display the result table
   End Sub

    Private Sub displayResults()

        Dim conn As New SqlConnection(connectionString)
        Dim daDetail As New SqlDataAdapter("tuition", conn)
        Dim dtDetail As New DataTable

        Dim dvDetail As New DataView(dtDetail)
        dvDetail.Sort = sortorder

        'Set a table width.
        tblResult.Width = Unit.Percentage(90.0)

        '****Create a new row for adding a table heading.
        Dim tableHeading3 As New TableRow

        If InStr(LCase(degreeSelected), "undergraduate") > 0 Then

            'Create and add the cells that contain the ugr tuition column heading text.
            Dim ugrTuitionHeading As New TableHeaderCell
            ugrTuitionHeading.Text = "Tuition"
            ugrTuitionHeading.HorizontalAlign = HorizontalAlign.Center
            ugrTuitionHeading.CssClass = "tablehead2"
        End If
        If InStr(LCase(degreeSelected), "others") > 0 Then
            'Create and add the cells that contain the others tuition column heading text.
            Dim otherTuitionHeading As New TableHeaderCell
            otherTuitionHeading.Text = "Tuition"
            otherTuitionHeading.HorizontalAlign = HorizontalAlign.Center
            otherTuitionHeading.CssClass = "tablehead2"
        End If

        'Create and add the cells that contain total heading text.
        Dim totalHeading2 As New TableHeaderCell
        ' totalHeading2.Text = "Total"
        totalHeading2.HorizontalAlign = HorizontalAlign.Center
        totalHeading2.CssClass = "tablehead2"

        'create link button web server control and add to cell for sorting
***** =============================================================********
        b.Text = "Total"
        b.CssClass = "classname"
***** =============================================================********


        ''****end of the heading text****''

    End Sub
    Protected Sub sortTotal_onclick(ByVal sender As Object, ByVal e As EventArgs) Handles b.Click
        lblShow.Text = lblShow.Text & "<br>sorttotal_onclick"
        sortorder = "total"
    End Sub
End Class
Question by:wk_lp
    LVL 28

    Expert Comment

    Shows how to sort a DataGrid's DataSet to provide sort functionality by clicking on the column headers.

    Create a new WebForm and add a DataGrid to it called DataGrid1.
    Right Click on the DataGrid and select the Property Builder, on the General section ensure that the
    Allow Sorting Option is Checked.
    Then Add this code to your VB Class:

    Imports System.Data.SqlClient
    Imports System.Data

    Public Class WebForm1
        Inherits System.Web.UI.Page

        Protected WithEvents Label1 As _
        Protected WithEvents DataGrid1 As _

        Private mstrSortCol As String

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

            'If this request is not a postback request
            'the bind to our DataSource
            If Not IsPostBack Then
            End If
        End Sub

        Private Sub BindData()

            Dim c As SqlClient.SqlConnection
            Dim da As SqlClient.SqlDataAdapter
            Dim ds As DataSet
            Dim strSQL As String
            Dim strCon As String

            'Set the SQL Query
            strSQL = "SELECT CompanyName, ContactName, " & _
              " ContactTitle, Phone, Fax FROM Customers "

            'If there is a Sort Column Specified then
            'Use it to sort the query
            If mstrSortCol <> "" Then
                strSQL += " ORDER BY " & mstrSortCol
            End If

            'Make Connection String.
            strCon = "server=localhost;database=Northwind;uid=sa;pwd=;"

            'Create and Open Connection
            c = New SqlClient.SqlConnection(strCon)

            'Perform Query and get the Results
            da = New SqlDataAdapter(strSQL, c)

            'Create a dataset
            ds = New DataSet()

            'Fill the Dataset

            'Bind the Grid to the Dataset
            DataGrid1.DataSource = ds
        End Sub

        Private Sub DataGrid1_SortCommand(ByVal source As Object, _
          ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) _
          Handles DataGrid1.SortCommand

            'Grab the Name of the item to sort by
            mstrSortCol = e.SortExpression()

            'reset the data
        End Sub
    End Class


    Author Comment

    sorry.  your reply is total irrelavant to my question.  I didn't ask how to sort a datagrid or a datalist.  I know how to do those.  I am asking how to sort a table web control that's generated manually in code behind page. I don't use any of the datagrid, datalist and repeater in this page.

    Thanks for the effort.

    Author Comment

    The way I tried was to query the database, put it in a dataview, pass a sort order to the dataview.  Then I loop through the dataview to create the table.  For the table's header column, I created and added link button control so that when it's clicked, it'll post back to the same page.  When it's clicked, it should run sortTotal_onclick sub.  Instead, an error occurred saying that object reference is not set to an instance of the object and the line number pointed to addhandler line.
    LVL 28

    Expert Comment

    Sorry I misunderstood your question

    Author Comment

    I have figured this out myself. Thanks for your attention.

    Author Comment

    I put the createButton function inside Page_init sub and that will recreate the control every time.

    Accepted Solution

    Question answered by asker or dialog valuable.
    Closed, 250 points refunded.
    ee_ai_construct (replacement part #xm34)
    Community Support Admin

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
    Introduction When many people think of the WebBrowser ( control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now