0

I have a combo box that I'm using to select a month out of a year. The months are provided through a List<> that I've set as the data source. I believe I'm going about this the wrong way.

Code So Far:

private void btnExport_Click(object sender, EventArgs e)
    {
        int month = 0; //just a default value
        if (cbMonth.SelectedText == "January")
            month = 1;
        else if (cbMonth.SelectedText == "Febuary")
            month = 2;
        else if (cbMonth.SelectedText == "March")
            month = 3;
        else if (cbMonth.SelectedText == "April")
            month = 4;
        else if (cbMonth.SelectedText == "May")
            month = 5;   
        else if (cbMonth.SelectedText == "June")
            month = 6;   
        else if (cbMonth.SelectedText == "July")
            month = 7;   
        else if (cbMonth.SelectedText == "August")
            month = 8;   
        else if (cbMonth.SelectedText == "September")
            month = 9;   
        else if (cbMonth.SelectedText == "October")
            month = 10;  
        else if (cbMonth.SelectedText == "November")
            month = 11;  
        else if (cbMonth.SelectedText == "December")
            month = 12;

        int year = Int32.Parse(mtbYear.Text);
        MessageBox.Show(month.ToString() + "   " + year.ToString()); // to check values

    }

My month never changes value and displays as 0. Which, I understand because I had given it the initial value of 0 in order to pass it to another method.

Question: How can I get the numeric value for the months when the user selects them from my combo box?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Jaskier
  • 1,075
  • 1
  • 10
  • 33
  • You should debug your code and check what is the value of cbMonth.SelectedText – MikkaRin Sep 10 '18 at 13:01
  • What kind of objects the list<> of months contains? – Lucian Sep 10 '18 at 13:01
  • Well what's the value of `cbMonth.SelectedText` - have you checked that? I'd also look into whether you can set the *value* of a combo box item separately from the text to display - I'd expect that to be possible, so you could set it all up appropriately and just fetch the value. – Jon Skeet Sep 10 '18 at 13:01
  • @MikkaRin , I have debugged it though, the value never changes from an empty string despite having the month selected. – Jaskier Sep 10 '18 at 13:05
  • @Lucian , my List<> contains the months of the year (as strings) – Jaskier Sep 10 '18 at 13:05
  • SelectedText is not what you appear to think it is. It is not `Text Selection` – Ňɏssa Pøngjǣrdenlarp Sep 10 '18 at 13:09
  • @Plutonix , I see. I also see that by default `SelectedText` will be set to an empty string. Is there something else I'd be able to use in order to accomplish what I'm trying to do? – Jaskier Sep 10 '18 at 13:12
  • are you using WPF or winforms? – Lucian Sep 10 '18 at 13:13
  • @Lucian , I'm using Winforms. I added the appropriate tag shortly after posting as I thought I had tagged it properly the first time! – Jaskier Sep 10 '18 at 13:14
  • If you are really using a datasource, selectedvalue, Selecteditem or maybe Selectedindex are what you want...selectedtext is the portion of the text in the text control that the user may or may not have highlighted and SELECTED – Ňɏssa Pøngjǣrdenlarp Sep 10 '18 at 13:17

6 Answers6

2

Show months in ComboBox:

comboBox1.DataSource = System.Globalization.CultureInfo.InvariantCulture
    .DateTimeFormat.MonthNames.Take(12).ToList();

Select current month:

comboBox1.SelectedIndex = DateTime.Now.Month - 1;

Get selected month:

MessageBox.Show($"Month: {comboBox1.SelectedIndex + 1} - {comboBox1.SelectedItem}");
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • You may ask why `Take(12)`, isn't it by default 12 months in the `MonthNames`? Read the [answer here.](https://stackoverflow.com/a/34079366/3110834). – Reza Aghaei Sep 10 '18 at 15:20
1

Hey whenever you see yourself using this many if elses, try to simplify the logic.

IDictionary<string, int> monthsDictionary = new Dictionary<string, int>()
                                        {
                                            {January,"1"},
                                            {February, "2"},
                                            {March,"3"}
                                            /* And so on */
                                        };

Declare this dictionary with the months you are using. Then you can just look at what the selected value of the cbo box is and use that as the key. Just make sure that the values in the cbo box match the keys in the dictionary. Like so.

private void btnExport_Click(object sender, EventArgs e)
{
    month = monthsDictionary[cbMonth.SelectedText];
    //This will give you the value of the key.
    //Ex. If march is chosen then 3 is what is given back as an int.

    int year = Int32.Parse(mtbYear.Text);
    MessageBox.Show(month.ToString() + "   " + year.ToString()); // to check values

}

I hope this helps!

Shanedolin
  • 59
  • 1
  • 7
  • You can load months into the ComboBox in a single line of code [like this](https://stackoverflow.com/a/52260593/3110834). – Reza Aghaei Sep 10 '18 at 15:06
1

Have you tried the SelectedValue of the Combobox?

private void btnExport_Click(object sender, EventArgs e)
    {
        int month = 0; //just a default value
        var monthNumber = DateTime.ParseExact((string)cbMonth.SelectedValue, "MMMM", CultureInfo.InvariantCulture).Month;

        int year = Int32.Parse(mtbYear.Text);
        MessageBox.Show(monthNumber.ToString() + "   " + year.ToString()); // to check values

    }

Don't forget to add try-catch for ParseExact

Lucian
  • 3,407
  • 2
  • 21
  • 18
  • Strange.. I must've been using `SelectedValue` incorrectly when I was first trying that method. Your answer worked for me! Thank you so much! – Jaskier Sep 10 '18 at 13:22
  • 1
    Numeric value of the month is selected index + 1. You don't need to parse the date time. Load combo box and get value easily [this way](https://stackoverflow.com/a/52260593/3110834). – Reza Aghaei Sep 10 '18 at 15:00
0

You may use ParseExact method of DateTime. Ex -

var monthNumber = DateTime.ParseExact(cbMonth.SelectedText, "MMMM", CultureInfo.InvariantCulture).Month;
Sham
  • 910
  • 8
  • 15
0

To get the numeric value from a list, i.e.

<asp:DropDownList ID="cbMonth" runat="server">
    <asp:ListItem Selected="True" Value="1" Text="January"></asp:ListItem>
    <asp:ListItem Value="2" Text="February"></asp:ListItem>
</asp:DropDownList>

The Selected value of this will give you the numeric value:

   private void btnExport_Click(object sender, EventArgs e)
        {
            int month = cbMonth.SelectedValue;
        }
cullimorer
  • 755
  • 1
  • 5
  • 23
0

Display the Month name at the font end but in value attribute store the month in number and when you select the month from combo box at that time in background you will get the month in digit

Akshay Jain
  • 790
  • 1
  • 7
  • 21