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

C# WinForm实现DataGridView按作者筛选书籍及显示全部功能

WinForm 实现作者筛选书籍功能

核心实现步骤

1. 定义数据实体类

先创建对应的数据类来存储作者和书籍信息,方便后续数据绑定:

public class Author
{
    public string Name { get; set; }
}

public class Book
{
    public string Title { get; set; }
    public string AuthorName { get; set; }
    public int PublishYear { get; set; }
    public decimal Price { get; set; }
}

2. 窗体初始化与数据绑定

在窗体加载事件中,准备数据源(实际项目可替换为数据库查询),给作者列表添加ALL选项,完成初始数据绑定:

// 窗体类中声明全局数据源变量
private List<Book> allBooks;
private List<Author> allAuthors;

private void Form1_Load(object sender, EventArgs e)
{
    // 模拟数据源(实际项目替换为数据库查询逻辑)
    allBooks = new List<Book>
    {
        new Book { Title = "C#入门指南", AuthorName = "张三", PublishYear = 2020, Price = 59.9m },
        new Book { Title = ".NET进阶实战", AuthorName = "张三", PublishYear = 2022, Price = 79.9m },
        new Book { Title = "WinForm开发详解", AuthorName = "李四", PublishYear = 2021, Price = 69.9m },
        new Book { Title = "数据库设计原理", AuthorName = "王五", PublishYear = 2019, Price = 49.9m }
    };

    allAuthors = new List<Author>
    {
        new Author { Name = "张三" },
        new Author { Name = "李四" },
        new Author { Name = "王五" }
    };

    // 在作者列表顶部插入"ALL"选项
    allAuthors.Insert(0, new Author { Name = "ALL" });

    // 绑定作者列表到第一个DataGridView
    dataGridViewAuthors.DataSource = allAuthors;
    dataGridViewAuthors.Columns["Name"].HeaderText = "作者名称";

    // 初始化显示全部书籍
    RefreshBookList(null);
}

3. 实现书籍列表刷新方法

封装一个通用方法,根据传入的作者名称筛选书籍并更新第二个DataGridView:

private void RefreshBookList(string authorName)
{
    List<Book> filteredBooks;
    if (string.IsNullOrEmpty(authorName) || authorName == "ALL")
    {
        // 显示全部书籍
        filteredBooks = allBooks;
    }
    else
    {
        // 筛选指定作者的书籍
        filteredBooks = allBooks.Where(b => b.AuthorName == authorName).ToList();
    }

    // 绑定筛选后的书籍数据
    dataGridViewBooks.DataSource = filteredBooks;
    // 设置列标题
    dataGridViewBooks.Columns["Title"].HeaderText = "书名";
    dataGridViewBooks.Columns["AuthorName"].HeaderText = "作者";
    dataGridViewBooks.Columns["PublishYear"].HeaderText = "出版年份";
    dataGridViewBooks.Columns["Price"].HeaderText = "价格";
}

4. 处理作者列表点击事件

给作者列表的CellClick事件绑定处理逻辑,点击作者名称时触发书籍筛选:

private void dataGridViewAuthors_CellClick(object sender, DataGridViewCellEventArgs e)
{
    // 排除点击表头的情况
    if (e.RowIndex >= 0)
    {
        DataGridViewRow selectedRow = dataGridViewAuthors.Rows[e.RowIndex];
        string selectedAuthor = selectedRow.Cells["Name"].Value.ToString();
        RefreshBookList(selectedAuthor);
    }
}

注意事项

  • 确保在WinForm设计器中,将两个DataGridView控件分别命名为dataGridViewAuthors和dataGridViewBooks,并将dataGridViewAuthors的CellClick事件关联到上述处理方法。
  • 如果使用数据库作为数据源,只需将模拟数据部分替换为对应的SQL查询或ORM框架查询逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:12:48