70 lines
2.1 KiB
C#
70 lines
2.1 KiB
C#
using System.Globalization;
|
|
|
|
namespace WinFormsLibrary1
|
|
{
|
|
public partial class DateInputControl : UserControl
|
|
{
|
|
public string DateFormat{ get; set; }
|
|
|
|
public DateInputControl()
|
|
{
|
|
InitializeComponent();
|
|
}
|
|
|
|
public DateTime Date
|
|
{
|
|
get
|
|
{
|
|
if(string.IsNullOrEmpty(textBoxDate.Text))
|
|
{
|
|
throw new Exception("Введите дату");
|
|
}
|
|
else if(string.IsNullOrEmpty(DateFormat))
|
|
{
|
|
throw new Exception("Шаблон не задан");
|
|
}
|
|
else if (Validate())
|
|
{
|
|
DateTime parsedDate;
|
|
if (DateTime.TryParseExact(textBoxDate.Text, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
|
|
{
|
|
return parsedDate;
|
|
}
|
|
}
|
|
throw new Exception("Неправильно введена дата");
|
|
}
|
|
set
|
|
{
|
|
if (!string.IsNullOrEmpty(DateFormat))
|
|
{
|
|
textBoxDate.Text = value.ToString(DateFormat);
|
|
} else
|
|
{
|
|
textBoxDate.Text = string.Empty;
|
|
}
|
|
}
|
|
}
|
|
|
|
private void TextBoxDate_TextChanged(object sender, EventArgs e)
|
|
{
|
|
ValidateDate();
|
|
}
|
|
|
|
private bool ValidateDate()
|
|
{
|
|
DateTime parsedDate;
|
|
|
|
if (DateTime.TryParseExact(textBoxDate.Text, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
|
|
{
|
|
errorLabel.Visible = false;
|
|
return true;
|
|
}
|
|
else
|
|
{
|
|
errorLabel.Visible = true;
|
|
errorLabel.Text = $"Неверный формат даты. Используйте формат {DateFormat}.";
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
} |