How to display the month number when choosing a month name

I have a list of months displayed in a drop down list. When choosing a specific month, I would like to indicate the month number in the text box.

For example, if I select January , I would like to display it as 01 , similarly for others.

This is an example of the code I wrote:

 string monthName = "january"; int i = DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture).Month; 
+4
source share
4 answers

Use this code to convert the selected month name to a number of months

 DateTime.ParseExact(monthName, "MMMM", CultureInfo.InvariantCulture).Month 

Need a line to fill?

 PadleftMonthNumberString.PadLeft(2, "0") 

References

Console Application Example

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string mnthname = "january"; int i = DateTime.ParseExact(mnthname, "MMMM", System.Globalization.CultureInfo.InvariantCulture).Month; Console.WriteLine(i.ToString()); Console.ReadLine(); } } } 
+13
source

Just trying to improvise (?) On hamlin11's answer, you can bypass the parsing code using the selectedindex + 1 drop-down list

+3
source

Here's an alternative that doesn't require any parsing or using a dropdown list index.

Create a list of month-to-month text, and then use it to create a dictionary to match text to value. Like this:

 var months = from m in Enumerable.Range(1, 12) select new { Value = m, Text = (new DateTime(2011, m, 1)).ToString("MMMM"), }; var list = months.Select(m => m.Text).ToArray(); var map = months.ToDictionary(m => m.Text, m => m.Value); 

Now the drop-down list can be populated from list , and any value that can be selected can be returned back to the value using map .

 var month = map["January"]; 

This generates the text, but does not analyze it, so it should work for any culture.

+3
source

Using a dropdown list index is a good option. You can also bind a dictionary to a drop-down list. Create a dictionary containing the names of the months for the current culture:

 var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames.Select ((m, i) => new { Key = string.Format("{0,2}", i + 1), Value = m, }); 

With data binding:

 ddl.DataSource = months; ddl.DataTextField = "Value"; ddl.DataValueField = "Key"; ddl.DataBind(); 
0
source

Source: https://habr.com/ru/post/1369263/


All Articles