C# - 从monthCalendar中保存字典中的所选日期

时间:2015-02-16 21:49:00

标签: c# dictionary monthcalendar

我用C#制作日历。为此我使用MonthCalendar(windows Forms)。 我想在日历上选择一个日期,并在该日期添加一些文本(如约会)。然后我想将日期和文本保存在字典中。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;

namespace agenda
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
    {

        //Selected only 1 date
        monthCalendar1.MaxSelectionCount = 1;
    }

    private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e)
    {
        var geselecteerdeDatum = monthCalendar1.SelectionRange.Start.ToString(); 

    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Dictionary<DateTime, string> dictionary = new Dictionary<DateTime, string>();
        dictionary.Add(geselecteerdeDatum, textBox1.Text);

        //show what is in the dictionary / print it in the console
        Console.WriteLine(geselecteerdeDatum);
        foreach (KeyValuePair<DateTime, string> kvp in dictionary)
        {
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
        }
    }

    public DateTime geselecteerdeDatum{ get; set; }
}

}

表单包含MonthCalendar,按钮和文本字段。 当我运行它时,我能够将一些文本保存到字典中。但MonthCalendar的日期不能正确保存到字典中。 每次它看起来像这样:

  Key = 1-1-0001 00:00:00, Value = message

有人知道如何在字典中获取所选日期吗?

1 个答案:

答案 0 :(得分:2)

更改dictionary.Add(geselecteerdeDatum, textBox1.Text);dictionary.Add(monthCalendar1.SelectionStart, textBox1.Text);

并且不需要多次设置MaxSelectionCount(您可以在表单设计器中执行此操作)。

var geselecteerdeDatum创建一个新的字符串变量(本地),与您的DateTime geselecteerdeDatum

无关