You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在DataGridView中分组?实现ROUTE 11至ROUTE 12的数据范围筛选

DataGridView 按ROUTE区间筛选展示数据的实现思路

以下是几种可行的实现方案,适配不同数据源和需求场景:

1. 基于数据源的直接过滤(最常用)

如果数据源是DataTable或支持数据视图的集合,直接通过筛选表达式过滤后绑定到DataGridView是最高效的方式:

  • 从搜索栏输入中提取ROUTE的数字部分(比如从"ROUTE 11"解析出11),计算区间上限(11+1=12)
  • 构造筛选条件,通过DataView的RowFilter实现数据过滤
  • 绑定过滤后的DataView到DataGridView

示例代码(C# WinForms):

// 假设搜索输入框为txtSearch,数据源为DataTable routeData
string searchText = txtSearch.Text.Trim();
if (int.TryParse(searchText.Replace("ROUTE ", ""), out int currentRoute))
{
    int nextRoute = currentRoute + 1;
    DataView filteredView = routeData.DefaultView;
    filteredView.RowFilter = $"ROUTE >= {currentRoute} AND ROUTE <= {nextRoute}";
    dataGridView1.DataSource = filteredView;
}

2. LINQ查询过滤集合数据源

如果数据源是强类型集合(比如List<RouteModel>),用LINQ直接筛选符合区间的数据后绑定:

  • 解析搜索输入的数字,确定筛选区间
  • 通过LINQ的Where方法过滤数据,再将结果绑定到DataGridView

示例代码:

// 假设RouteModel包含int类型的Route属性
string searchText = txtSearch.Text.Trim();
if (int.TryParse(searchText.Replace("ROUTE ", ""), out int currentRoute))
{
    int nextRoute = currentRoute + 1;
    var filteredList = routeList.Where(m => m.Route >= currentRoute && m.Route <= nextRoute).ToList();
    dataGridView1.DataSource = filteredList;
}

3. 自定义分组展示(需视觉分组时)

如果需要将ROUTE 11和ROUTE 12的数据分组显示(比如添加分组标题行),可以手动实现分组逻辑:

  • 先过滤出符合区间的数据,按ROUTE字段分组
  • 遍历每个分组,先添加自定义的分组标题行(设置区分样式,比如加粗背景色),再添加该分组下的所有数据行
  • 需处理DataGridView的行样式,区分分组行和数据行

4. 利用DataGridView内置筛选(简单场景)

WinForms的DataGridView支持列筛选功能,可通过代码主动设置ROUTE列的筛选条件:

  • 确保DataGridView的AllowUserToFilter属性为true(部分版本需手动开启)
  • 找到ROUTE列的筛选控件,设置筛选范围为currentRoute到nextRoute
  • 该方式适合无复杂逻辑的场景,但灵活性不如直接过滤数据源

内容的提问来源于stack exchange,提问作者Uğur ARPACI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:24:29