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


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
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

wk_lpAuthor Commented:
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.
wk_lpAuthor Commented:
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.
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Sorry I misunderstood your question
wk_lpAuthor Commented:
I have figured this out myself. Thanks for your attention.
wk_lpAuthor Commented:
I put the createButton function inside Page_init sub and that will recreate the control every time.
Question answered by asker or dialog valuable.
Closed, 250 points refunded.
ee_ai_construct (replacement part #xm34)
Community Support Admin

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.