Goal:
My goal is to filter datagrid
by selected month from dropdown
options.
January, February, March etc...
I'd like to know if there are easier methods to my current method..
Code:
public Schedule()
{
InitializeComponent();
RefreshGrid();
Dictionary<string, string> allOptions = new Dictionary<string, string>();
allOptions.Add("1", "All");
allOptions.Add("2", "January");
allOptions.Add("3", "February");
allOptions.Add("4", "March");
allOptions.Add("5", "April");
allOptions.Add("6", "May");
allOptions.Add("7", "June");
allOptions.Add("8", "July");
allOptions.Add("9", "August");
allOptions.Add("10", "September");
allOptions.Add("11", "October");
allOptions.Add("12", "November");
allOptions.Add("13", "December");
Months.DataSource = new BindingSource(allOptions, null);
Months.DisplayMember = "Value";
Months.ValueMember = "Key";
}
public void RefreshGrid()
{
string value = "";
// Select All
if(Months.SelectedIndex == 0)
{
value = "";
}
// Select * from January
if(Months.SelectedIndex == 1)
{
value = " where month(date_purchased) = 1;";
}
// Select * from February
if (Months.SelectedIndex == 2)
{
value = " where month(date_purchased) = 2;";
}
//... and son on...
// MySQL connection string
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
//Select query
using (var mySqlDataAdapter = new MySqlDataAdapter("select * from table "+ value +";", conn))
{
using (var dataSet = new DataSet())
{
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
//Assign headers to Data Grid View
scheduleData.DataSource = DS.Tables[0];
scheduleData.Columns[0].HeaderText = "ID";
scheduleData.Columns[1].HeaderText = "Equipment Name";
scheduleData.Columns[2].HeaderText = "Date Purchased";
//Set visibility to false for the columns to work in the background
scheduleData.Columns[0].Visible = false;
}
}
}
}
private void Months_SelectedIndexChanged(object sender, EventArgs e)
{
RefreshGrid();
}
This idea does work - but Seems like there is too much unnecessarily code. But I cannot think of an alternative.