Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

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

Posted on 2004-11-11
8
Medium Priority
?
320 Views
Last Modified: 2012-08-13
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
 
 
0
Comment
Question by:wk_lp
  • 4
  • 2
7 Comments
 
LVL 28

Expert Comment

by:iboutchkine
ID: 12554980
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

0
 

Author Comment

by:wk_lp
ID: 12555071
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.
0
 

Author Comment

by:wk_lp
ID: 12555093
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.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 28

Expert Comment

by:iboutchkine
ID: 12555112
Sorry I misunderstood your question
0
 

Author Comment

by:wk_lp
ID: 12556655
I have figured this out myself. Thanks for your attention.
0
 

Author Comment

by:wk_lp
ID: 12556746
I put the createButton function inside Page_init sub and that will recreate the control every time.
0
 

Accepted Solution

by:
ee_ai_construct earned 0 total points
ID: 12589444
Question answered by asker or dialog valuable.
Closed, 250 points refunded.
ee_ai_construct (replacement part #xm34)
Community Support Admin
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Screencast - Getting to Know the Pipeline
Kernel Data Recovery is a renowned Data Recovery solution provider which offers wide range of softwares for both enterprise and home users with its cost-effective solutions. Let's have a quick overview of the journey and data recovery tools range he…

564 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