问题
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