using System; using System.Globalization; using System.Windows.Forms; namespace KryukovLib { public partial class DateBoxWithNull : UserControl { public event EventHandler? CombinedEvent; public Exception? Error; public DateBoxWithNull() { InitializeComponent(); } public DateTime? Value { get { if (!checkBoxNull.Checked) { if (string.IsNullOrEmpty(textBoxDate.Text)) { throw new NotFilledException("Text box can't be empty, click checkbox if value must be empty!"); } if (DateTime.TryParseExact(textBoxDate.Text, "dd.MM.yyyy", null, DateTimeStyles.None, out DateTime parsedDate)) { return parsedDate; } else { throw new ParseException($"Wrong format <{textBoxDate.Text}>!"); } } return null; } set { bool isNull = value is null; checkBoxNull.Checked = isNull; textBoxDate.Text = isNull ? string.Empty : value?.ToString("dd.MM.yyyy"); } } private void TextBoxDate_TextChanged(object sender, EventArgs e) { CombinedEvent?.Invoke(sender, e); } private void CheckBoxNull_CheckedChanged(object sender, EventArgs e) { textBoxDate.Enabled = !checkBoxNull.Checked; CombinedEvent?.Invoke(sender, e); } } }