列表框(ListBox)和DataGridView是Windows Forms中常用的控件。通过列表框过滤DataGridView中的数据是一种常见的交互方式,允许用户通过选择列表框中的项来动态筛选DataGridView中显示的数据。
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
public class FilterForm : Form
{
private DataGridView dataGridView1;
private ListBox listBox1;
private DataTable originalData;
public FilterForm()
{
// 初始化控件
dataGridView1 = new DataGridView { Dock = DockStyle.Fill };
listBox1 = new ListBox { Dock = DockStyle.Left, Width = 150 };
// 添加控件到窗体
Controls.Add(dataGridView1);
Controls.Add(listBox1);
// 加载数据
LoadData();
// 绑定事件
listBox1.SelectedIndexChanged += ListBox1_SelectedIndexChanged;
}
private void LoadData()
{
// 创建示例数据
originalData = new DataTable();
originalData.Columns.Add("ID", typeof(int));
originalData.Columns.Add("Name", typeof(string));
originalData.Columns.Add("Category", typeof(string));
originalData.Rows.Add(1, "Item 1", "Category A");
originalData.Rows.Add(2, "Item 2", "Category B");
originalData.Rows.Add(3, "Item 3", "Category A");
originalData.Rows.Add(4, "Item 4", "Category C");
originalData.Rows.Add(5, "Item 5", "Category B");
// 绑定DataGridView
dataGridView1.DataSource = originalData;
// 填充ListBox
var categories = originalData.AsEnumerable()
.Select(row => row.Field<string>("Category"))
.Distinct()
.OrderBy(c => c)
.ToList();
listBox1.Items.Add("(All Categories)"); // 添加"全部"选项
foreach (var category in categories)
{
listBox1.Items.Add(category);
}
listBox1.SelectedIndex = 0; // 默认选择"全部"
}
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0) // 选择了"全部"
{
dataGridView1.DataSource = originalData;
return;
}
string selectedCategory = listBox1.SelectedItem.ToString();
var filteredData = originalData.AsEnumerable()
.Where(row => row.Field<string>("Category") == selectedCategory)
.CopyToDataTable();
dataGridView1.DataSource = filteredData;
}
}
原因:可能是筛选条件不正确或数据绑定方式有问题 解决:
CopyToDataTable()
前检查是否有结果原因:直接操作DataTable可能在大数据量时效率不高 解决:
原因:数据源中有重复值 解决:
Distinct()
方法去除重复项private BindingSource bindingSource = new BindingSource();
private void LoadData()
{
// ... 同前 ...
bindingSource.DataSource = originalData;
dataGridView1.DataSource = bindingSource;
}
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0)
{
bindingSource.Filter = null;
return;
}
string selectedCategory = listBox1.SelectedItem.ToString();
bindingSource.Filter = $"Category = '{selectedCategory.Replace("'", "''")}'";
}
这种方法更高效,因为它不需要创建新的DataTable,而是直接在原始数据上应用筛选。
没有搜到相关的文章