| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- using System;
- using System.Text.RegularExpressions;
- using System.Windows.Forms;
- namespace WindowsFormsApp4
- {
- public partial class ClientEditForm : Form
- {
- private int? clientId;
- private bool isEditMode;
- public ClientEditForm()
- {
- InitializeComponent();
- isEditMode = false;
- lblTitle.Text = "Добавление клиента";
- AttachEventHandlers();
- }
- public ClientEditForm(int id, string lastName, string firstName, string middleName, string phone)
- {
- InitializeComponent();
- isEditMode = true;
- clientId = id;
- lblTitle.Text = "Редактирование клиента";
- txtLastName.Text = lastName;
- txtFirstName.Text = firstName;
- txtMiddleName.Text = middleName;
- txtPhone.Text = phone;
- AttachEventHandlers();
- }
- private void AttachEventHandlers()
- {
- btnSave.Click += BtnSave_Click;
- btnCancel.Click += BtnCancel_Click;
- }
- private bool ValidateFields()
- {
- if (string.IsNullOrWhiteSpace(txtLastName.Text))
- {
- MessageBox.Show("Введите фамилию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- txtLastName.Focus();
- return false;
- }
- if (string.IsNullOrWhiteSpace(txtFirstName.Text))
- {
- MessageBox.Show("Введите имя", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- txtFirstName.Focus();
- return false;
- }
- string phone = txtPhone.Text.Trim();
- if (string.IsNullOrWhiteSpace(phone))
- {
- MessageBox.Show("Введите номер телефона", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- txtPhone.Focus();
- return false;
- }
- Regex phoneRegex = new Regex(@"^(\+7|8)[0-9]{10}$");
- if (!phoneRegex.IsMatch(phone))
- {
- MessageBox.Show("Некорректный номер телефона. Формат: +7XXXXXXXXXX или 8XXXXXXXXXX",
- "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- txtPhone.Focus();
- return false;
- }
- return true;
- }
- private void BtnSave_Click(object sender, EventArgs e)
- {
- if (!ValidateFields())
- return;
- bool result;
- if (isEditMode && clientId.HasValue)
- {
- result = DatabaseHelper.UpdateClient(
- clientId.Value,
- txtLastName.Text.Trim(),
- txtFirstName.Text.Trim(),
- txtMiddleName.Text.Trim(),
- txtPhone.Text.Trim()
- );
- }
- else
- {
- int newId = DatabaseHelper.AddClient(
- txtLastName.Text.Trim(),
- txtFirstName.Text.Trim(),
- txtMiddleName.Text.Trim(),
- txtPhone.Text.Trim()
- );
- result = newId > 0;
- }
- if (result)
- {
- this.DialogResult = DialogResult.OK;
- this.Close();
- }
- else
- {
- MessageBox.Show("Ошибка при сохранении", "Ошибка",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- private void BtnCancel_Click(object sender, EventArgs e)
- {
- this.DialogResult = DialogResult.Cancel;
- this.Close();
- }
- }
- }
|