/
DaNN26
/
SQLProvider
Обзор
Документация
Войти
/
DaNN26
/
SQLProvider
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
ProductEditForm.cs
361 строка
13 KB
DaNN
Добавьте файлы проекта.
27 май 2026, 12:50
27 май 2026, 12:50
4fe37b9
Код
Авторство
О чём код?
using System; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Windows.Forms; namespace Demo { internal partial class ProductEditForm : Form { private const string PlaceholderPath = @"Images\picture.png"; private int productId; private bool isEdit; private string oldPhotoPath; private string selectedImagePath; public ProductEditForm(int selectedProductId) { productId = selectedProductId; isEdit = productId > 0; InitializeComponent(); AppHelper.SetAppIcon(this); LoadLookups(); if (isEdit) { LoadProduct(); } else { PrepareNewProductMode(); } } private void PrepareNewProductMode() { Text = "Добавление товара"; idLabel.Visible = false; idTextBox.Visible = false; deleteButton.Visible = false; SetPhoto(AppHelper.LoadImage(PlaceholderPath)); } private void LoadLookups() { FillCombo(categoryComboBox, "SELECT CategoryId, CategoryName FROM dbo.Categories ORDER BY CategoryName", "CategoryId", "CategoryName"); FillCombo(manufacturerComboBox, "SELECT ManufacturerId, ManufacturerName FROM dbo.Manufacturers ORDER BY ManufacturerName", "ManufacturerId", "ManufacturerName"); FillCombo(supplierComboBox, "SELECT SupplierId, SupplierName FROM dbo.Suppliers ORDER BY SupplierName", "SupplierId", "SupplierName"); FillCombo(unitComboBox, "SELECT UnitId, UnitName FROM dbo.Units ORDER BY UnitName", "UnitId", "UnitName"); } private void FillCombo(ComboBox comboBox, string sql, string idColumn, string nameColumn) { var table = DatabaseHelper.GetData(sql); comboBox.Items.Clear(); foreach (DataRow row in table.Rows) { comboBox.Items.Add(new ComboItem(Convert.ToInt32(row[idColumn]), row[nameColumn].ToString())); } if (comboBox.Items.Count > 0) { comboBox.SelectedIndex = 0; } } private void LoadProduct() { var table = DatabaseHelper.GetData( "SELECT ProductId, Article, ProductName, UnitId, Price, SupplierId, ManufacturerId, CategoryId, " + "Discount, Quantity, Description, PhotoPath FROM dbo.Products WHERE ProductId = " + productId); if (table.Rows.Count == 0) { AppHelper.ShowError("Товар не найден."); DialogResult = DialogResult.Cancel; Close(); return; } var row = table.Rows[0]; idTextBox.Text = row["ProductId"].ToString(); articleTextBox.Text = row["Article"].ToString(); nameTextBox.Text = row["ProductName"].ToString(); descriptionTextBox.Text = row["Description"].ToString(); priceNumeric.Value = Convert.ToDecimal(row["Price"]); quantityNumeric.Value = Convert.ToDecimal(row["Quantity"]); discountNumeric.Value = Convert.ToDecimal(row["Discount"]); oldPhotoPath = row["PhotoPath"].ToString(); SelectCombo(categoryComboBox, Convert.ToInt32(row["CategoryId"])); SelectCombo(manufacturerComboBox, Convert.ToInt32(row["ManufacturerId"])); SelectCombo(supplierComboBox, Convert.ToInt32(row["SupplierId"])); SelectCombo(unitComboBox, Convert.ToInt32(row["UnitId"])); SetPhoto(AppHelper.LoadImage(oldPhotoPath)); } private void SelectCombo(ComboBox comboBox, int id) { foreach (object item in comboBox.Items) { var comboItem = item as ComboItem; if (comboItem != null && comboItem.Id == id) { comboBox.SelectedItem = comboItem; return; } } } private int GetSelectedId(ComboBox comboBox) { var item = comboBox.SelectedItem as ComboItem; return item == null ? 0 : item.Id; } private void PhotoButton_Click(object sender, EventArgs e) { var dialog = new OpenFileDialog(); dialog.Filter = "Изображения|*.jpg;*.jpeg;*.png;*.bmp"; if (dialog.ShowDialog() == DialogResult.OK) { selectedImagePath = dialog.FileName; SetPhoto(AppHelper.LoadImage(selectedImagePath)); } } private void SaveButton_Click(object sender, EventArgs e) { if (!ValidateFields()) { return; } try { SaveProduct(); DialogResult = DialogResult.OK; Close(); } catch (Exception ex) { AppHelper.ShowError("Не удалось сохранить товар.\n" + ex.Message); } } private bool ValidateFields() { if (string.IsNullOrWhiteSpace(articleTextBox.Text)) { AppHelper.ShowError("Введите артикул товара."); return false; } if (string.IsNullOrWhiteSpace(nameTextBox.Text)) { AppHelper.ShowError("Введите наименование товара."); return false; } if (GetSelectedId(categoryComboBox) == 0 || GetSelectedId(manufacturerComboBox) == 0 || GetSelectedId(supplierComboBox) == 0 || GetSelectedId(unitComboBox) == 0) { AppHelper.ShowError("Заполните категорию, производителя, поставщика и единицу измерения."); return false; } return true; } private void SaveProduct() { var article = articleTextBox.Text.Trim(); var photoPath = SaveSelectedImage(article); DatabaseHelper.ExecuteCommand(isEdit ? UpdateSql(article, photoPath) : InsertSql(article, photoPath)); if (isEdit && !string.IsNullOrWhiteSpace(selectedImagePath) && photoPath != oldPhotoPath) { DeleteOldPhoto(oldPhotoPath); } } private string UpdateSql(string article, string photoPath) { return "UPDATE dbo.Products SET " + "Article = " + AppHelper.SqlText(article) + ", " + "ProductName = " + AppHelper.SqlText(nameTextBox.Text) + ", " + "UnitId = " + GetSelectedId(unitComboBox) + ", " + "Price = " + Number(priceNumeric) + ", " + "SupplierId = " + GetSelectedId(supplierComboBox) + ", " + "ManufacturerId = " + GetSelectedId(manufacturerComboBox) + ", " + "CategoryId = " + GetSelectedId(categoryComboBox) + ", " + "Discount = " + Number(discountNumeric) + ", " + "Quantity = " + Number(quantityNumeric) + ", " + "Description = " + AppHelper.SqlText(descriptionTextBox.Text) + ", " + "PhotoPath = " + AppHelper.SqlText(photoPath) + " " + "WHERE ProductId = " + productId; } private string InsertSql(string article, string photoPath) { return "INSERT INTO dbo.Products " + "(Article, ProductName, UnitId, Price, SupplierId, ManufacturerId, CategoryId, Discount, Quantity, Description, PhotoPath) VALUES (" + AppHelper.SqlText(article) + ", " + AppHelper.SqlText(nameTextBox.Text) + ", " + GetSelectedId(unitComboBox) + ", " + Number(priceNumeric) + ", " + GetSelectedId(supplierComboBox) + ", " + GetSelectedId(manufacturerComboBox) + ", " + GetSelectedId(categoryComboBox) + ", " + Number(discountNumeric) + ", " + Number(quantityNumeric) + ", " + AppHelper.SqlText(descriptionTextBox.Text) + ", " + AppHelper.SqlText(photoPath) + ")"; } private string Number(NumericUpDown input) { return input.Value.ToString(CultureInfo.InvariantCulture); } private string SaveSelectedImage(string article) { if (string.IsNullOrWhiteSpace(selectedImagePath)) { return oldPhotoPath; } var imagesDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images"); Directory.CreateDirectory(imagesDirectory); var safeArticle = article; foreach (char invalidChar in Path.GetInvalidFileNameChars()) { safeArticle = safeArticle.Replace(invalidChar, '_'); } var fileName = safeArticle + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg"; var destinationPath = Path.Combine(imagesDirectory, fileName); using (var source = Image.FromFile(selectedImagePath)) { using (var resized = new Bitmap(300, 200)) { using (var graphics = Graphics.FromImage(resized)) { graphics.Clear(Color.White); graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(source, 0, 0, 300, 200); } resized.Save(destinationPath, ImageFormat.Jpeg); } } return @"Images\" + fileName; } private void DeleteButton_Click(object sender, EventArgs e) { try { if (ProductUsedInOrders()) { AppHelper.ShowError("Товар присутствует в заказе. Удаление запрещено."); return; } if (!DeleteConfirmed()) { return; } DatabaseHelper.ExecuteCommand("DELETE FROM dbo.Products WHERE ProductId = " + productId); DeleteOldPhoto(oldPhotoPath); DialogResult = DialogResult.OK; Close(); } catch (Exception ex) { AppHelper.ShowError("Не удалось удалить товар.\n" + ex.Message); } } private bool ProductUsedInOrders() { var table = DatabaseHelper.GetData("SELECT COUNT(*) AS CountItems FROM dbo.OrderItems WHERE ProductId = " + productId); return Convert.ToInt32(table.Rows[0]["CountItems"]) > 0; } private bool DeleteConfirmed() { var result = MessageBox.Show( "Удалить выбранный товар?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); return result == DialogResult.Yes; } private void DeleteOldPhoto(string photoPath) { if (string.IsNullOrWhiteSpace(photoPath)) { return; } var fullPath = Path.GetFullPath(AppHelper.GetFilePath(photoPath)); var imagesDirectory = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images")); var fileName = Path.GetFileName(fullPath); if (fileName.ToLowerInvariant() == "picture.png") { return; } if (fullPath.StartsWith(imagesDirectory, StringComparison.OrdinalIgnoreCase) && File.Exists(fullPath)) { File.Delete(fullPath); } } private void SetPhoto(Image image) { if (photoPictureBox.Image != null) { photoPictureBox.Image.Dispose(); } photoPictureBox.Image = image; } private void CancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } protected override void OnFormClosed(FormClosedEventArgs e) { if (photoPictureBox != null && photoPictureBox.Image != null) { photoPictureBox.Image.Dispose(); } base.OnFormClosed(e); } } }