ASP.NET使用VB实现GridView排序功能遇到问题求解
GridView 排序功能实现步骤
- 调整
Page_Load逻辑,避免每次回发重复加载数据
原有逻辑每次页面回发都会触发数据重绑定,会覆盖排序事件的处理逻辑,修改为仅首次加载时调用绑定:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ' 仅首次页面加载时调用绑定,回发时由对应事件触发 If Not IsPostBack Then loadgrid() End If End Sub
- 新增排序状态存储属性
由于WebForm是无状态的,需要用ViewState存储当前的排序字段和排序方向:
' 存储当前排序表达式 Private Property SortExpression() As String Get If ViewState("SortExpression") Is Nothing Then ' 可修改为你需要的默认排序字段 ViewState("SortExpression") = "EmployerName" End If Return ViewState("SortExpression").ToString() End Get Set(ByVal value As String) ViewState("SortExpression") = value End Set End Property ' 存储当前排序方向 Private Property SortDirection() As SortDirection Get If ViewState("SortDirection") Is Nothing Then ViewState("SortDirection") = SortDirection.Ascending End If Return CType(ViewState("SortDirection"), SortDirection) End Get Set(ByVal value As SortDirection) ViewState("SortDirection") = value End Set End Property
- 修改
GridDataLoader方法,传入排序参数
注意你原有代码漏了给GridView指定DataSource,需要补充:
Public Sub GridDataLoader() ' 拼接完整排序语句 Dim sortDir = If(SortDirection = SortDirection.Ascending, "ASC", "DESC") Dim fullSortExpression = $"{SortExpression} {sortDir}" ' 传入排序参数调用查询方法 Dim dataTable = Employer.GetEmployers(eEmployer, chkLegacy.Checked, fullSortExpression) ' 补充指定数据源,原有代码缺少这步会导致绑定失败 gvEmployer.DataSource = dataTable gvEmployer.DataBind() End Sub
- 修改
GetEmployers方法,新增排序逻辑
在SQL语句最后拼接ORDER BY排序规则:
Public Function GetEmployers(ByVal eEmployer As tblEmployer, ByVal All As Boolean, Optional ByVal sortExpression As String = Nothing) As DataTable Dim query = "" ' 保留你原有SQL查询逻辑 query = "select employer.EmployerID as EmployerId, employer.Employer_Name as EmployerName, // 剩余查询逻辑保持不变 on (employer.Modified_by=tum.UserID) where employer.LegacyID IS NULL and address.ValidityTo is null" Dim params = "" If All = False Then query += " AND employer.ValidityTo is null" End If If (params.Trim() IsNot "") Then query = query & params End If ' 新增排序逻辑:如果有传入排序参数,拼接ORDER BY语句 If Not String.IsNullOrEmpty(sortExpression) Then query &= $" ORDER BY {sortExpression}" End If data.setSQLCommand(query, CommandType.Text) Return data.Filldata End Function
- 添加GridView的Sorting事件处理方法
处理点击列标题触发的排序事件:
Protected Sub gvEmployer_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs) Handles gvEmployer.Sorting ' 点击当前排序字段时切换排序方向 If e.SortExpression = SortExpression Then SortDirection = If(SortDirection = SortDirection.Ascending, SortDirection.Descending, SortDirection.Ascending) Else ' 切换新排序字段,默认使用升序 SortExpression = e.SortExpression SortDirection = SortDirection.Ascending End If ' 重新绑定带排序的数据 loadgrid() End Sub
内容的提问来源于stack exchange,提问作者Julker Nien Akib
相关产品推荐
相关产品推荐

