C# DatagridView search/filter

白昼怎懂夜的黑 提交于 2020-01-06 20:01:47

问题


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);
    }
}

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.


回答1:


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());
}

Hope it helps.




回答2:


Solution 1: If your data is changing frequently and you want up to date data you are OK to use the same code as yours.

Solution 2: Get the data from datasource - Store into DataTable - Filter the data as per requirement and set DataGridView source to dataset.

You can also refer this



来源:https://stackoverflow.com/questions/38077568/c-sharp-datagridview-search-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!