Solved

dynamic gridview not sorting

Posted on 2008-10-14
9
1,119 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
ID: 22713082
  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
ID: 22713108
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
ID: 22713222
isent your Column that should have a  SortExpression ?
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

Author Comment

by:wthomson
ID: 22713330
The column does have a sortExpression
0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 22713432
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
ID: 22713513
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
ID: 22713665
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
ID: 22713886
I need to make this work
0
 
LVL 18

Expert Comment

by:David Robitaille
ID: 22714035
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

828 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