Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a combobox with Months and numbers for months

Tags:

c#

combobox

wpf

I am working on a WPF project and I have a months combobox that should contain months from Jan to Dec. I managed to do it by following snippet;

var americanCulture = new CultureInfo("en-US");
ddlMonth.Items.AddRange(americanCulture.DateTimeFormat.MonthNames);

And got the list as;

January
February
March
....

But I want them to populate as ;

01 - January
02 - February
03 - March
.....

Any ideas how proceed it with for loop? I am newbie to C#. Thanks

like image 868
AbdulAziz Avatar asked Dec 08 '22 16:12

AbdulAziz


2 Answers

      var americanCulture = new CultureInfo("en-US");
      var count = 1;
      //.Take(12) in the foreach below because apparantly MonthNames returns 13
      //elements of which the last one is empty
      foreach (var month in americanCulture.DateTimeFormat.MonthNames.Take(12))
      {    
      DropDownList1.Items.Add(new ListItem{Text = count.ToString("00") + "-" + month});
      count++;
      }
like image 155
Thousand Avatar answered Dec 11 '22 06:12

Thousand


Noo. Why are you doing it in the backend. Take advantage of wpf and use the xaml.

Let me try to explain how to do this.

  1. First create a dependency property for the Months. If you haven't used dependency properties. You should research them now http://wpftutorial.net/DependencyProperties.html. In below code I am setting the default value of the property to a list of the months via new PropertyMetadata(new CultureInfo("en-US").DateTimeFormat.MonthNames.Take(12).ToList())). So now we can obtain this property from the xaml.

    public partial class MainWindow : Window
    {
    public static readonly DependencyProperty MonthsProperty = DependencyProperty.Register(
        "Months", 
        typeof(List<string>), 
        typeof(MainWindow), 
        new PropertyMetadata(new CultureInfo("en-US").DateTimeFormat.MonthNames.Take(12).ToList()));
    
    public List<string> Months
    {
        get
        {
            return (List<string>)this.GetValue(MonthsProperty);
        }
    
        set
        {
            this.SetValue(MonthsProperty, value);
        }
    }
    public MainWindow()
    {
        InitializeComponent();            
    }
    

    }

  2. You need a converter. http://wpftutorial.net/ValueConverters.html if not familiar with them. What the converter is going to do is for every value in the list we are going to modify the string to get the desired result you want. So create a new class for the value converter.

    [ValueConversion(typeof(List<string>), typeof(List<string>))]
    public class MonthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
        //get the list of months from the object sent in    
        List<string> months = (List<string>)value;
    
        //manipulate the data index starts at 0 so add 1 and set to 2 decimal places
        if (months != null && months.Count > 0)
        {
            for (int x = 0; x < months.Count; x++)
            {
                months[x] = (x + 1).ToString("D2") + " - " + months[x];
            }
        }
    
        return months;
    }
    
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
    
    #endregion
    

    }

  3. Set it up in the xaml. Create a name for your window ie x:Name="testWindow", this is so can better access it when binding. Setup your namespace so you can get the converter. xmlns:Main="clr-namespace:WpfApplication4". Add the converter to the resources, . In the combobox bind the itemssource to your dependency property Months and send it through the converter.

    <Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="testwindow"
        xmlns:Main="clr-namespace:WpfApplication4"
        Title="MainWindow" Height="350" Width="525">
    
        <Window.Resources>
            <Main:MonthConverter x:Key="MonthConverter"/>
        </Window.Resources>
    
        <Grid>
            <ComboBox ItemsSource="{Binding ElementName=testwindow,Path=Months, Converter={StaticResource MonthConverter}}" HorizontalAlignment="Left" Margin="197,107,0,0" VerticalAlignment="Top" Width="120"/>
    
        </Grid>
    </Window>
    
like image 32
user892381 Avatar answered Dec 11 '22 05:12

user892381