Solved

dynamic gridview not sorting

Posted on 2008-10-14
9
1,111 Views
Last Modified: 2013-11-07
I have the dynamic gridview displaying correctly BUT it will not sort, it either goes to a 'ie page not found' if "EnableSortingAndPagingCallbacks = false" or if EnableSortingAndPagingCallbacks = true then nothing happens.

<asp:GridView ID="grdReportAssetsSummary" runat="server" AllowPaging="True" AllowSorting="True" 

CssClass="datagrid" AutoGenerateColumns="False" Width="100%" PageSize="1000" DataKeyNames="ConnectoryID"

PagerSettings-FirstPageText="First" PagerSettings-LastPageText="Last" PagerSettings-Mode="NumericFirstLast" PagerSettings-Position="TopAndBottom">

<RowStyle CssClass="grdItem" />

<AlternatingRowStyle CssClass="grdAltItem" />

<FooterStyle CssClass="grdFooter"></FooterStyle>

<HeaderStyle CssClass="grdHeader" Wrap="True"></HeaderStyle>

<PagerStyle CssClass="grdFooter"></PagerStyle>

</asp:GridView>

==================================================

Imports System.Data

Imports System.Web.UI.WebControls

Imports Core.Business
 

Partial Class ReportView1

	Inherits Core.BasePage
 

	Public posNaic, posPerson, posQual, posLicense, posOwner As Integer
 

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

		lblMsg.Text = String.Empty

		'If grdReportAssetsSummary.SortExpression = "" Then

		'	grdReportAssetsSummary.Sort("CompanyName", SortDirection.Ascending)

		'End If

		'If (Not Page.IsPostBack) Then

		lblSubHeader.Text = "Assets  Summary"

		Dim portalid As Integer = Common.ConvNullToZero(Session.Item("PortalID"))

		BindData(portalid)

		'End If

	End Sub
 

	Private Sub BindData(ByVal PortalID As Integer)

		If String.IsNullOrEmpty(Request.QueryString("reportid")) Then

			Throw New Exception("reportid querystring parameter is not present")

		End If

		If String.IsNullOrEmpty(Request.QueryString("month")) Then

			Throw New Exception("month querystring parameter is not present")

		End If

		If String.IsNullOrEmpty(Request.QueryString("year")) Then

			Throw New Exception("year querystring parameter is not present")

		End If

		If String.IsNullOrEmpty(Request.QueryString("flds")) Then

			Throw New Exception("Field List querystring parameter is not present")

		End If
 

		Dim reportid As String = Request.QueryString("reportid")

		Dim month As String = Request.QueryString("month")

		Dim year As String = Request.QueryString("year")

		Dim fieldsSelected As String = Request.QueryString("flds")
 
 

		posNaic = 0

		posPerson = 0
 
 

		'1 - Company:

		Dim nameColumn As New HyperLinkField()

		nameColumn.DataNavigateUrlFields = New String() {"connectoryId"}

		nameColumn.DataTextField = "CompanyName"

		nameColumn.SortExpression = "CompanyName"

		nameColumn.DataNavigateUrlFormatString = "http://connectory.com/search/profile_view.aspx?connectoryId={0}"

		nameColumn.Text = "{0}"

		nameColumn.Target = "_Profile"

		nameColumn.HeaderText = "Company"

		grdReportAssetsSummary.Columns.Add(nameColumn)
 
 

		'2 - Year Established:  

		If Mid(fieldsSelected, 2, 1) = "1" Then

			Dim yearestablishedColumn As New BoundField()

			yearestablishedColumn.DataField = "yearestablished"

			yearestablishedColumn.SortExpression = "yearestablished"

			yearestablishedColumn.HeaderText = "Year Established"

			grdReportAssetsSummary.Columns.Add(yearestablishedColumn)

		End If
 

		'3 - Website:  

		If Mid(fieldsSelected, 3, 1) = "1" Then

			Dim URLColumn As New BoundField()

			URLColumn.DataField = "URL"

			URLColumn.HeaderText = "Website"

			grdReportAssetsSummary.Columns.Add(URLColumn)

		End If
 

		'4 - Local Employees:

		If Mid(fieldsSelected, 4, 1) = "1" Then

			Dim LOCALEMPLOYEESColumn As New BoundField()

			LOCALEMPLOYEESColumn.DataField = "LOCALEMPLOYEES"

			LOCALEMPLOYEESColumn.HeaderText = "Local Employees"

			grdReportAssetsSummary.Columns.Add(LOCALEMPLOYEESColumn)

		End If
 
 

		'5 - Corporate Employees:   

		If Mid(fieldsSelected, 5, 1) = "1" Then

			Dim CORPEMPLOYEESColumn As New BoundField()

			CORPEMPLOYEESColumn.DataField = "CORPEMPLOYEES"

			CORPEMPLOYEESColumn.HeaderText = "Corp Employees"

			grdReportAssetsSummary.Columns.Add(CORPEMPLOYEESColumn)

		End If
 
 

		'6- Annual Revenue: 

		If Mid(fieldsSelected, 6, 1) = "1" Then

			Dim ANNUALREVENUEColumn As New BoundField()

			ANNUALREVENUEColumn.DataField = "ANNUALREVENUE"

			ANNUALREVENUEColumn.HeaderText = "Annual Revenue"

			grdReportAssetsSummary.Columns.Add(ANNUALREVENUEColumn)

		End If
 
 
 

		'7 - Industry Category / Asset Type:  

		'industrycategory

		If Mid(fieldsSelected, 7, 1) = "1" Then

			Dim industrycategoryColumn As New BoundField()

			industrycategoryColumn.DataField = "industrycategory"

			industrycategoryColumn.HeaderText = "Industry Category"

			grdReportAssetsSummary.Columns.Add(industrycategoryColumn)

		End If
 
 

		'8 - Key Personnel: 

		If Mid(fieldsSelected, 8, 1) = "1" Then

			Dim KeyPersonnelColumn As New BoundField()

			KeyPersonnelColumn.DataField = "keyPerson"

			KeyPersonnelColumn.HeaderText = "Key Personnel"

			grdReportAssetsSummary.Columns.Add(KeyPersonnelColumn)

			posPerson = 0

			Dim tfieldV As Integer

			For tfieldV = 1 To 7

				If Mid(fieldsSelected, tfieldV, 1) = "1" Then posPerson += 1

			Next

		End If
 
 

		'9 - Local Address:  

		If Mid(fieldsSelected, 9, 1) = "1" Then

			Dim LocalAddressColumn As New BoundField()

			LocalAddressColumn.DataField = "LocalAddressFull"

			LocalAddressColumn.HeaderText = "Local Address"

			grdReportAssetsSummary.Columns.Add(LocalAddressColumn)

		End If
 

		'10 -Mailing Address:    

		If Mid(fieldsSelected, 10, 1) = "1" Then

			Dim MailingAddressColumn As New BoundField()

			MailingAddressColumn.DataField = "MailingAddressFull"

			MailingAddressColumn.HeaderText = "Mailing Address"

			grdReportAssetsSummary.Columns.Add(MailingAddressColumn)

		End If
 

		'11 - United States Phone:  

		If Mid(fieldsSelected, 11, 1) = "1" Then

			Dim PhoneColumn As New BoundField()

			PhoneColumn.DataField = "Phone"

			PhoneColumn.HeaderText = "Phone"

			grdReportAssetsSummary.Columns.Add(PhoneColumn)

		End If
 

		'12 - Industry Codes - NAICS:    

		If Mid(fieldsSelected, 12, 1) = "1" Then

			Dim NAICSCodesColumn As New BoundField()

			NAICSCodesColumn.DataField = "NAICSCodes"

			NAICSCodesColumn.HeaderText = "NAICS Codes"

			grdReportAssetsSummary.Columns.Add(NAICSCodesColumn)

			posNaic = 0

			Dim tfieldV As Integer

			For tfieldV = 1 To 11

				If Mid(fieldsSelected, tfieldV, 1) = "1" Then posNaic += 1

			Next

		End If
 

		'13 - Customer Base - Industry Sector:

		If Mid(fieldsSelected, 13, 1) = "1" Then

			Dim industrycatColumn As New BoundField()

			industrycatColumn.DataField = "industrycategory"

			industrycatColumn.HeaderText = "Industry Category"

			grdReportAssetsSummary.Columns.Add(industrycatColumn)

		End If
 

		'14 - Certifications - Quality:

		If Mid(fieldsSelected, 14, 1) = "1" Then

			Dim qualCertColumn As New BoundField()

			qualCertColumn.DataField = "qualCert"

			qualCertColumn.HeaderText = "Quality Cert"

			grdReportAssetsSummary.Columns.Add(qualCertColumn)

			posQual = 0

			Dim tfieldV As Integer

			For tfieldV = 1 To 13

				If Mid(fieldsSelected, tfieldV, 1) = "1" Then posQual += 1

			Next

		End If
 

		'15 - Certifications - License:

		If Mid(fieldsSelected, 15, 1) = "1" Then

			Dim licCertColumn As New BoundField()

			licCertColumn.DataField = "licCert"

			licCertColumn.HeaderText = "License Cert"

			grdReportAssetsSummary.Columns.Add(licCertColumn)

			posLicense = 0

			Dim tfieldV As Integer

			For tfieldV = 1 To 14

				If Mid(fieldsSelected, tfieldV, 1) = "1" Then posLicense += 1

			Next

		End If
 

		'16 - Certifications - Ownership: 

		If Mid(fieldsSelected, 16, 1) = "1" Then

			Dim ownerCertColumn As New BoundField()

			ownerCertColumn.DataField = "ownerCert"

			ownerCertColumn.HeaderText = "Owner Cert"

			grdReportAssetsSummary.Columns.Add(ownerCertColumn)

			posOwner = 0

			Dim tfieldV As Integer

			For tfieldV = 1 To 15

				If Mid(fieldsSelected, tfieldV, 1) = "1" Then posOwner += 1

			Next

		End If
 
 

		Dim StartDate As DateTime = DateTime.Parse(String.Format("{0}/{1}/{2} 12:00:00 AM", month, 1, year))

		Dim EndDate As DateTime = DateTime.Parse(String.Format("{0}/{1}/{2} 11:59:59 PM", month, DateTime.DaysInMonth(year, month), year))

		Dim objReportData As New Portal.Data.ReportData

		Dim Data As DataSet = objReportData.GetAssetSummary(StartDate, EndDate, PortalID)

		'Dim SicCodes As DataSet = objReportData.GetSICCodes(StartDate, EndDate, PortalID)

		Dim NaicCodes As DataSet = objReportData.GetNAICCodes(StartDate, EndDate, PortalID)

		Dim keyPersonCodes As DataSet = objReportData.GetkeyPersonCodes(PortalID)

		Dim keyQualCerts As DataSet = objReportData.GetkeyQualCerts(StartDate, EndDate, PortalID)

		Dim keyLicense As DataSet = objReportData.GetkeyLicense(StartDate, EndDate, PortalID)

		Dim keyOwner As DataSet = objReportData.GetkeyOwner(StartDate, EndDate, PortalID)
 

		grdReportAssetsSummary.DataSource = Data
 

		ViewState("grdReportAssetsSummary_DataSource") = grdReportAssetsSummary.DataSource

		'ViewState("SicCodes") = SicCodes

		ViewState("NaicCodes") = NaicCodes

		ViewState("keyPersonCodes") = keyPersonCodes

		ViewState("keyQualCerts") = keyQualCerts

		ViewState("keyLicense") = keyLicense

		ViewState("keyOwner") = keyOwner
 

		grdReportAssetsSummary.AllowPaging = True

		grdReportAssetsSummary.AllowSorting = True

		grdReportAssetsSummary.AutoGenerateColumns = False

		Dim dknT() As String = {"ConnectoryId"}

		grdReportAssetsSummary.DataKeyNames = dknT

		grdReportAssetsSummary.EnableSortingAndPagingCallbacks = True

		grdReportAssetsSummary.EnableViewState = True

		grdReportAssetsSummary.PageSize = "1000"

		'grdReportAssetsSummary.Sort("CompanyName", SortDirection.Descending)
 
 

		grdReportAssetsSummary.DataBind()

		lblRecordCount.Text = String.Format("Item Count: {0}", Data.Tables(0).Rows.Count)

	End Sub
 

	Public Sub grdReportAssetsSummary_RowDataBound(ByVal sender As Object, ByVal e As Web.UI.WebControls.GridViewRowEventArgs) _

	 Handles grdReportAssetsSummary.RowDataBound
 

		'This is hit once for every record

		If e.Row.RowType = DataControlRowType.DataRow Then

			Dim connectoryid As Integer = grdReportAssetsSummary.DataKeys(e.Row.RowIndex).Value

			'If posSic > 0 Then

			'	Try

			'		Dim SicCodes As DataSet = ViewState("SicCodes")

			'		Dim scodes As DataRow() = SicCodes.Tables(0).Select(String.Format("ConnectoryID={0}", connectoryid), "connectoryid asc")

			'		Dim sbscodes As StringBuilder = New StringBuilder(scodes.Length)

			'		For i As Integer = 0 To scodes.Length - 1

			'			sbscodes.AppendFormat("{0} - {1}<BR />", scodes(i).Item(2).ToString().Trim(), scodes(i).Item(4).ToString().Trim())

			'		Next

			'		e.Row.Cells.Item(posSic).Text = scodes.ToString()

			'	Catch ex As Exception

			'	End Try

			'End If

			If posNaic > 0 Then

				Try

					Dim NaicCodes As DataSet = ViewState("NaicCodes")

					Dim ncodes As DataRow() = NaicCodes.Tables(0).Select(String.Format("ConnectoryID={0}", connectoryid), "connectoryid asc")

					Dim sbncodes As StringBuilder = New StringBuilder(ncodes.Length)

					For i As Integer = 0 To ncodes.Length - 1

						sbncodes.AppendFormat("{0} - {1}<BR />", ncodes(i).Item(2).ToString().Trim(), ncodes(i).Item(3).ToString().Trim())

					Next

					e.Row.Cells.Item(posNaic).Text = sbncodes.ToString()

				Catch ex As Exception

				End Try

			End If
 

			If posPerson > 0 Then

				Try

					Dim keyPersonCodes As DataSet = ViewState("keyPersonCodes")

					Dim kpcodes As DataRow() = keyPersonCodes.Tables(0).Select(String.Format("ConnectoryID={0}", connectoryid), "connectoryid asc")

					Dim sbkpcodes As StringBuilder = New StringBuilder(kpcodes.Length)

					For i As Integer = 0 To kpcodes.Length - 1

						sbkpcodes.AppendFormat("{0} - {1}<BR />", kpcodes(i).Item(2).ToString().Trim(), kpcodes(i).Item(3).ToString().Trim())

					Next

					e.Row.Cells.Item(posPerson).Text = sbkpcodes.ToString()

				Catch ex As Exception

				End Try

			End If
 

			If posQual > 0 Then

				Try

					Dim keyQualCerts As DataSet = ViewState("keyQualCerts")

					Dim qucodes As DataRow() = keyQualCerts.Tables(0).Select(String.Format("ConnectoryID={0}", connectoryid), "connectoryid asc")

					Dim sbqucodes As StringBuilder = New StringBuilder(qucodes.Length)

					For i As Integer = 0 To qucodes.Length - 1

						sbqucodes.AppendFormat("{0} - {1}<BR />", qucodes(i).Item(2).ToString().Trim(), qucodes(i).Item(3).ToString().Trim())

					Next

					e.Row.Cells.Item(posQual).Text = sbqucodes.ToString()

				Catch ex As Exception

				End Try

			End If
 

			If posLicense > 0 Then

				Try

					Dim keyLicense As DataSet = ViewState("keyLicense")

					Dim liccodes As DataRow() = keyLicense.Tables(0).Select(String.Format("ConnectoryID={0}", connectoryid), "connectoryid asc")

					Dim sbliccodes As StringBuilder = New StringBuilder(liccodes.Length)

					For i As Integer = 0 To liccodes.Length - 1

						sbliccodes.AppendFormat("{0} - {1}<BR />", liccodes(i).Item(2).ToString().Trim(), liccodes(i).Item(3).ToString().Trim())

					Next

					e.Row.Cells.Item(posLicense).Text = sbliccodes.ToString()

				Catch ex As Exception

				End Try

			End If
 

			If posOwner > 0 Then

				Try

					Dim keyOwner As DataSet = ViewState("keyOwner")

					Dim owncodes As DataRow() = keyOwner.Tables(0).Select(String.Format("ConnectoryID={0}", connectoryid), "connectoryid asc")

					Dim sbowncodes As StringBuilder = New StringBuilder(owncodes.Length)

					For i As Integer = 0 To owncodes.Length - 1

						sbowncodes.AppendFormat("{0} - {1}<BR />", owncodes(i).Item(2).ToString().Trim(), owncodes(i).Item(3).ToString().Trim())

					Next

					e.Row.Cells.Item(posOwner).Text = sbowncodes.ToString()

				Catch ex As Exception

				End Try

			End If
 

		End If

	End Sub
 

	Protected Sub grdReportAssetsSummary_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs) _

	 Handles grdReportAssetsSummary.Sorting
 

		GridViewSortExpression = e.SortExpression

		SetSortGridView(GridViewSortExpression(), GetSortDirection())

	End Sub
 

	Private Property GridViewSortDirection() As String

		Get

			If String.IsNullOrEmpty(ViewState("SortDirection")) Then

				Return "DESC"

			Else

				Return ViewState("SortDirection")

			End If

		End Get

		Set(ByVal value As String)

			ViewState("SortDirection") = value

		End Set

	End Property
 

	Private Function GetSortDirection() As String

		Select Case GridViewSortDirection

			Case "ASC"

				GridViewSortDirection = "DESC"

			Case "DESC"

				GridViewSortDirection = "ASC"

		End Select

		Return GridViewSortDirection

	End Function
 

	Private Property GridViewSortExpression() As String

		Get

			If String.IsNullOrEmpty(ViewState("SortExpression")) Then

				Return "CompanyName"

			Else

				Return ViewState("SortExpression")

			End If

		End Get

		Set(ByVal value As String)

			ViewState("SortExpression") = value

		End Set

	End Property
 

	Protected Sub grdReportAssetsSummary_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdReportAssetsSummary.PageIndexChanging

		' set page index for paging

		grdReportAssetsSummary.PageIndex = e.NewPageIndex

		' set sort order

		SetSortGridView(GridViewSortExpression(), GridViewSortDirection())

	End Sub
 

	Protected Sub SetSortGridView(ByVal SortExpression As String, ByVal SortDirection As String)

		Dim m_DataSet As System.Data.DataSet = ViewState("grdReportAssetsSummary_DataSource")

		If Not m_DataSet Is Nothing Then

			Dim m_DataView As New System.Data.DataView(m_DataSet.Tables(0))

			m_DataView.Sort = SortExpression + " " + SortDirection

			grdReportAssetsSummary.DataSource = m_DataView

			grdReportAssetsSummary.DataBind()

		End If

	End Sub
 

End Class

Open in new window

0
Comment
Question by:wthomson
  • 5
  • 4
9 Comments
 
LVL 18

Accepted Solution

by:
David Robitaille earned 500 total points
Comment Utility
  1. EnableSortingAndPagingCallbacks = true
  2. in your Private Sub Page_Load add a
    If Not (Page.IsPostBack) Then
you are gattin nothing because the page load stuff is run a each postback  and the BindData(portalid) is run each time.


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

		If Not (Page.IsPostBack) Then
 

                   lblMsg.Text = String.Empty

		'If grdReportAssetsSummary.SortExpression = "" Then

		'	grdReportAssetsSummary.Sort("CompanyName", SortDirection.Ascending)

		'End If

		'If (Not Page.IsPostBack) Then

		lblSubHeader.Text = "Assets  Summary"

		Dim portalid As Integer = Common.ConvNullToZero(Session.Item("PortalID"))

		BindData(portalid)

		'End If

                  end if

	End Sub

Open in new window

0
 

Author Comment

by:wthomson
Comment Utility
That is not it, I have tried both ways AND the 'Private Sub Page_Load ' is NOT being hit at all when the header/sort is clicked
0
 
LVL 18

Assisted Solution

by:David Robitaille
David Robitaille earned 500 total points
Comment Utility
isent your Column that should have a  SortExpression ?
0
 

Author Comment

by:wthomson
Comment Utility
The column does have a sortExpression
0
Free Trending Threat Insights Every Day

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.

 
LVL 18

Expert Comment

by:David Robitaille
Comment Utility
only nameColumn and yearestablishedColumn? that the only ones you want to sort?
And why did create your column progarmaticly????  it<s cimpler to do this in the aspx file, no?
 
 
0
 

Author Comment

by:wthomson
Comment Utility
It has to be dynamic, the page before allows the user to select the columns. when I am trying to use it, I only have the name column selected and it won't sort. If I select name and yearestablished, neither will sort or do annything.
0
 
LVL 18

Expert Comment

by:David Robitaille
Comment Utility
why you dont just toggle the visibilyty of the columns of the gridview and let asp.net`s gridview do the job instead of handeling grdReportAssetsSummary.Sorting event?

 
0
 

Author Comment

by:wthomson
Comment Utility
I need to make this work
0
 
LVL 18

Expert Comment

by:David Robitaille
Comment Utility
the fact the 'Private Sub Page_Load ' is NOT being hit at all when the header/sort is clicked is part fo your problems.
normaly, hitting the header/sort trigger with enableSortingAndPagingCallbacks set to true should trigger  the page load (that part of the post back).
Also, you should not have to handle the grdReportAssetsSummary.Sorting the way you do, the grid view should be able to play with it`s datasource and sort it correctly. what if you remove that  grdReportAssetsSummary.Sorting event?

 
 
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

762 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

12 Experts available now in Live!

Get 1:1 Help Now