C# 类似Excel筛选功能的DataGridView
时间: 2024-05-27 18:08:47 浏览: 17
可以使用 DataGridView 的筛选功能来实现类似于 Excel 的筛选功能。以下是实现步骤:
1. 将 DataGridView 的 AllowUserToOrderColumns 和 AllowUserToResizeColumns 属性设置为 true,以允许用户拖动和调整列的大小。
2. 将 DataGridView 的 AllowUserToAddRows 和 AllowUserToDeleteRows 属性设置为 false,以防止用户添加或删除行。
3. 在 DataGridView 的 ColumnHeaderMouseClick 事件中添加以下代码,以在单击列标题时显示筛选菜单:
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
Rectangle headerRectangle = dataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, true);
Point menuLocation = new Point(headerRectangle.Left, headerRectangle.Bottom);
contextMenuStrip1.Show(dataGridView1.PointToScreen(menuLocation));
}
}
4. 在筛选菜单中添加菜单项,并在其单击事件处理程序中添加以下代码,以筛选 DataGridView 中的数据:
private void menuItemFilter_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
if (menuItem != null)
{
string filterText = menuItem.Text;
DataGridViewColumn column = dataGridView1.Columns[contextMenuStrip1.Tag.ToString()];
column.HeaderCell.Value = filterText;
dataGridView1.Filter(column.DataPropertyName, filterText);
}
}
5. 添加以下扩展方法,以在 DataGridView 中筛选数据:
public static void Filter(this DataGridView dataGridView, string columnName, string filterText)
{
if (dataGridView.DataSource != null)
{
(dataGridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("{0} LIKE '{1}%'", columnName, filterText);
}
}
这样,你就可以在 DataGridView 中实现类似于 Excel 的筛选功能了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)