I'm making a calendar with C#. For this I use MonthCalendar (windows Forms). I want to select a date on the calendar and add some text to that date (like an appointment). And then I want to save the date and the text in a dictionary.
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; }
}
}
The form contains a MonthCalendar, a button and a text field. When I run this, I'm able to save some text to the dictionary. But the date from the MonthCalendar won't save correctly to the dictionary. Everytime it looks like this:
Key = 1-1-0001 00:00:00, Value = message
Does anybody know how I can get the selected date in the dictionary?
Change dictionary.Add(geselecteerdeDatum, textBox1.Text);
to dictionary.Add(monthCalendar1.SelectionStart, textBox1.Text);
And there is no need to set MaxSelectionCount
more than once (you can do it in the form designer).
var geselecteerdeDatum
creates a new string variable (local) which has nothing to do with your DateTime geselecteerdeDatum