C#DatagridView搜索

C#DatagridView搜索

本文介绍了C#DatagridView搜索/过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,我正在尝试使用基于组合框值的filter datagridview。最初,我使用数据库中所有所需的值加载了datagridview,现在我希望每当用户从组合框选择任何内容时,DataGridView中的值也应更改。一个对我有用的解决方案是在每个组合框值更改时请求数据库,并且它可以正常工作...为此附有代码

I am new to c#, I am trying to use filter the datagridview based on combobox value. Initially I loaded datagridview with all the desired values from database, now I want whenever user selects anything from combobox, the values in DataGridView should also change. One Solution which works for me is to request the database on each combobox value change and it works... code is attached for that

DataRowView view = (DataRowView)comboBox2.SelectedItem;
int year = (int) view.Row["Year"];
DataTable dt = new DataTable();
if (this.OpenConnection() == true)
{
    String query = "Select * from yearly where year = "+year;
    MySqlCommand cmd = new MySqlCommand(query, connection);

    using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
    {
        da.Fill(dt);
    }
}

但是,有什么方法可以不请求数据库一次又一次 ?并且我可以根据组合框值过滤datagridview。任何教程或链接都可以使用。

but, is there any way to not request the database again and again ? and I can filter the datagridview based on combobox value. Any tutorial or link will work.

推荐答案

在组合框的SelectionChangeCommitted事件中:

In combobox's SelectionChangeCommitted event:

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
    (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Year= '{0}'", comboBox1.SelectedItem.ToString());
}

希望它会有所帮助。

这篇关于C#DatagridView搜索/过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 17:38