PIbd-32_Rogashova_E.A._COP_1/COPWinForms/ComponentTBox.cs

157 lines
4.2 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace COPWinForms
{
public partial class ComponentTBox : UserControl
{
//Шаблон для textbox
private string? pattern;
//Пример ввода
private string example = "example@gmail.com";
private event Action? _errorOccured;
public string Error { get; private set; }
public ComponentTBox()
{
InitializeComponent();
Error = string.Empty;
}
//Публичное свойство для получения и заполнения шаблона
public string? Pattern
{
get { return pattern; }
set { pattern = value; }
}
//Публичное свойство для получения и заполнения значения
public string? TextBoxValue
{
get
{
if (pattern != null) {
Regex regex = new Regex(Pattern);
bool isValid = regex.IsMatch(textBox.Text);
if (isValid)
{
return textBox.Text;
}
else
{
Error = "Is not email";
_errorOccured?.Invoke();
return null;
}
}
else {
Error = "No pattern";
_errorOccured?.Invoke();
return null;
}
}
set
{
if (pattern != null)
{
Regex regex = new Regex(Pattern);
bool isValid = regex.IsMatch(value);
if (isValid)
{
textBox.Text = value;
}
else
{
Error = "Is not email";
_errorOccured?.Invoke();
return;
}
}
else
{
Error = "No pattern";
_errorOccured?.Invoke();
return;
}
}
}
//Метод для заполнения примера
public void setExample(string str)
{
if (pattern != null)
{
Regex regex = new Regex(Pattern);
bool isValid = regex.IsMatch(str);
if (isValid)
{
example = str;
}
}
else
{
Error = "No pattern";
_errorOccured?.Invoke();
return;
}
}
//ToolTip для вывода примера
private void textBox_Enter(object sender, EventArgs e)
{
int VisibleTime = 3000; //in milliseconds
ToolTip tt = new ToolTip();
tt.Show(example, textBox, 0, 20, VisibleTime);
}
private EventHandler _explicitEvent;
public event EventHandler ExplicitEvent
{
add
{
_explicitEvent += value;
}
remove
{
_explicitEvent -= value;
}
}
public event Action AnErrorOccurred
{
add { _errorOccured += value; }
remove { _errorOccured -= value; }
}
//событие при смене значения
private void textBox_TextChanged(object sender, EventArgs e)
{
try
{
_explicitEvent?.Invoke(sender, e);
}
catch (Exception ex)
{
Error = ex.Message;
_errorOccured?.Invoke();
}
}
}
}