Search code examples
c#sql-servercombobox

c# check if the value of the combo box is equals to the month


So let's say I want to check whether the selected value of combo box with the month then filter the table of my mysql database to only display the specified month, how can i possibly do this?

Here's what I Have so far

    if (combox.text == "MONTH HERE")
{
    string query= "SELECT * from mytable  WHERE Month LIKE '%MONTHHERE'"
    SqlDataAdapter sda= new SqlDataAdapter (query, con)
    DataSet set= new DataSet
    sda.Fill(set);
    table.DataSource=set
}

for example I want to check and display only the month of "January". Following my code above :

if (combox.text == "January")
{
    string query= "SELECT * from mytable WHERE Month LIKE '%January'"
    SqlDataAdapter sda= new SqlDataAdapter (query, con)
    DataSet set= new DataSet
    sda.Fill(set);
    table.DataSource=set
}

My code is working but I want to know if there is another way of checking instead of manually writing different if statement for each month? Thank you!

edit:

    if (combox.text == "Month1" || combox.text == "Month2")
{
    string query= "SELECT * from mytable WHERE Month LIKE '%Month1%' OR Month Like %Month2%"
    SqlDataAdapter sda= new SqlDataAdapter (query, con)
    DataSet set= new DataSet
    sda.Fill(set);
    table.DataSource=set
}

Solution

  • You can pass the month as parameter to the query, there is no need of multiple if else.

    And when you pass the parameter just make sure you’re using the parameterized query.

    Please avoid select *, instead selected the required columns with alias.