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

WPF C#中如何隐藏DataGrid中Active属性为False的行

嘿,我来帮你搞定这个需求!要隐藏DataGrid里active=false的客户行,有两种常用方案,优先推荐第一种,更高效优雅:

方案一:从数据源层面过滤(推荐)

直接把active=false的客户从数据源里排除,再绑定到DataGrid,比手动操作行要靠谱得多,还能避免后续数据变化时还要手动同步行的可见性。

如果你用的是WPF(绑定ObservableCollection)

假设你的客户数据存在ObservableCollection<Customer>里,用LINQ过滤后重新绑定就行;要是需要动态响应active属性变化,用CollectionViewSource做过滤更方便:

// 简单过滤:直接取active为true的客户
var activeCustomers = customers.Where(c => c.Active).ToList();
dataGrid.ItemsSource = activeCustomers;

// 动态过滤(当客户的active属性变化时自动更新显示)
CollectionViewSource viewSource = new CollectionViewSource();
viewSource.Source = customers;
// 添加过滤规则
viewSource.Filter += (sender, e) => {
    var customer = e.Item as Customer;
    e.Accepted = customer != null && customer.Active;
};
dataGrid.ItemsSource = viewSource.View;

如果你用的是WinForms(绑定DataTable)

用DataView来做过滤就行,非常简单:

// 假设你的客户数据存在customerTable里
DataView activeCustomerView = new DataView(customerTable);
// 设置过滤条件
activeCustomerView.RowFilter = "Active = true";
dataGrid.DataSource = activeCustomerView;
方案二:直接操作DataGrid行(适合特殊场景)

要是你必须保留完整的数据源,只是单纯隐藏行,那可以遍历DataGrid的行,检查对应客户的active属性,然后设置行的可见性:

WPF版本

private void HideInactiveCustomers()
{
    foreach (var item in dataGrid.Items)
    {
        var customer = item as Customer;
        if (customer != null && !customer.Active)
        {
            // 获取对应的行容器
            var row = dataGrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
            if (row != null)
            {
                row.Visibility = Visibility.Collapsed;
            }
        }
    }
}

注意:如果WPF的DataGrid开启了虚拟化(默认是开的),ItemContainerGenerator.ContainerFromItem可能拿不到行对象,这时候要么先滚动到对应行,要么关闭虚拟化(数据量大时不推荐)。

WinForms版本

private void HideInactiveCustomers()
{
    foreach (DataGridViewRow row in dataGrid.Rows)
    {
        // 从单元格或者绑定的对象里获取active值
        bool isActive = Convert.ToBoolean(row.Cells["Active"].Value);
        if (!isActive)
        {
            row.Visible = false;
        }
    }
}

小提示

  • 优先用过滤数据源的方式,不管是WPF还是WinForms,都更符合最佳实践,尤其是数据量大的时候,性能比手动操作行好太多。
  • 如果需要客户的active属性变化后自动更新显示,用WPF的CollectionViewSource或者WinForms的DataView会自动处理,不用再手动调用隐藏方法。

内容的提问来源于stack exchange,提问作者marcoschwepp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:37:40