Link to home
Start Free TrialLog in
Avatar of wk_lp
wk_lp

asked on

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

Hi,

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.

Ping

***** =============================================================********
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.
        InitializeComponent()
    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 b.click, addressof sorttotal_click

        If Not Page.IsPostBack Then
            showChoices()
        Else
        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
        displayResults()
   End Sub

    Private Sub displayResults()

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

        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"
            tableHeading3.Cells.Add(ugrTuitionHeading)
        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"
            tableHeading3.Cells.Add(otherTuitionHeading)
        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"
        totalHeading2.Controls.Add(b)
***** =============================================================********
        tableHeading3.Cells.Add(totalHeading2)

        tblResult.Rows.Add(tableHeading3)


        ''****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"
        displayResults()
    End Sub
End Class
 
 
Avatar of iboutchkine
iboutchkine

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 _
        System.Web.UI.WebControls.Label
    Protected WithEvents DataGrid1 As _
        System.Web.UI.WebControls.DataGrid

    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
            BindData()
        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)
        c.Open()

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

        'Create a dataset
        ds = New DataSet()

        'Fill the Dataset
        da.Fill(ds)

        'Bind the Grid to the Dataset
        DataGrid1.DataSource = ds
        DataGrid1.DataBind()
    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
        BindData()
    End Sub
End Class

Avatar of wk_lp

ASKER

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.
Avatar of wk_lp

ASKER

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.
Sorry I misunderstood your question
Avatar of wk_lp

ASKER

I have figured this out myself. Thanks for your attention.
Avatar of wk_lp

ASKER

I put the createButton function inside Page_init sub and that will recreate the control every time.
ASKER CERTIFIED SOLUTION
Avatar of ee_ai_construct
ee_ai_construct
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial