C# Month Combobox - Setting Selecteditem

Asked

Viewed 22 times

0

I have to create a Combobox only with the months of the year to handle the system’s paying bills. So far so good, the problem is that the client wanted to be selected the current month in Load.

I want to bring the data dynamically, without using an ENUM with the handwritten values.

How is the code:


private void LoadComboBoxMonths()
{
    string[] arrayMonths = DateTimeFormatInfo.CurrentInfo.GetMonthName;
    forech(var item in arrayMonths)
    {
        Months.Add(item.ToUpper());
    }
    
    cboMesCorrente.DataSource = Monhts
    cboMesCorrente.SelectedItem = DateTime.Now.Month.ToString("MMMM");
}   

That one Selecteitem above does not work.

1 answer

0

So I had used the DateTimeFormatInfo.CurrentInfo.GetMonthName to bring the months to the Array and worked out.

So I thought and used the same only, instead of using an Array of Strings to then pass the values to the List I preferred to pass directly to the List.

How It Came Out in the End:

private List<string> Months = new List<string>();

private void LoadComboBoxMonths()
{

    for(int i = 1; i<=13; i++)
    {
        Months.Add(DateTimeFormatInfo.CurrentInfo.GetMonthName(i).ToUpper();
    }
    
    cboMesCorrente.DataSource = Months;
    cboMesCorrente.SelectedItem = DateTimeFormatInfo.CurrentInfo.GetMonthName(DateTime.Now.Month).ToUpper();
}

It seems like a simple solution, but I hit my head a lot and I couldn’t find anything in the network to help. I hope it can help other people so they don’t suffer all day like I did. And I also hope that they do not remove, because if I had an article or question like that I would not have suffered so much. I’ve wasted a whole day doing this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.