/
Ermoha
/
SqlDataDrivers
Обзор
Документация
Войти
/
Ermoha
/
SqlDataDrivers
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
ProductEditForm.cs
347 строк
13 KB
ermoh
Добавьте файлы проекта.
26 май 2026, 22:28
26 май 2026, 22:28
b563253
Код
Авторство
О чём код?
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 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 { Text = "Добавление товара"; idLabel.Visible = false; idTextBox.Visible = false; deleteButton.Visible = false; SetPhoto(AppHelper.LoadImage(@"Images\picture.png")); } } 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) { DataTable 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() { DataTable 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; } DataRow 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) { ComboItem comboItem = item as ComboItem; if (comboItem != null && comboItem.Id == id) { comboBox.SelectedItem = comboItem; return; } } } private int GetSelectedId(ComboBox comboBox) { ComboItem item = comboBox.SelectedItem as ComboItem; if (item == null) { return 0; } return item.Id; } private void PhotoButton_Click(object sender, EventArgs e) { OpenFileDialog 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 { string article = articleTextBox.Text.Trim(); string photoPath = SaveSelectedImage(article); string price = priceNumeric.Value.ToString(CultureInfo.InvariantCulture); int quantity = Convert.ToInt32(quantityNumeric.Value); int discount = Convert.ToInt32(discountNumeric.Value); if (isEdit) { string sql = "UPDATE dbo.Products SET " + "Article = " + AppHelper.SqlText(article) + ", " + "ProductName = " + AppHelper.SqlText(nameTextBox.Text) + ", " + "UnitId = " + GetSelectedId(unitComboBox) + ", " + "Price = " + price + ", " + "SupplierId = " + GetSelectedId(supplierComboBox) + ", " + "ManufacturerId = " + GetSelectedId(manufacturerComboBox) + ", " + "CategoryId = " + GetSelectedId(categoryComboBox) + ", " + "Discount = " + discount + ", " + "Quantity = " + quantity + ", " + "Description = " + AppHelper.SqlText(descriptionTextBox.Text) + ", " + "PhotoPath = " + AppHelper.SqlText(photoPath) + " " + "WHERE ProductId = " + productId; DatabaseHelper.ExecuteCommand(sql); if (!string.IsNullOrWhiteSpace(selectedImagePath) && photoPath != oldPhotoPath) { DeleteOldPhoto(oldPhotoPath); } } else { string sql = "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) + ", " + price + ", " + GetSelectedId(supplierComboBox) + ", " + GetSelectedId(manufacturerComboBox) + ", " + GetSelectedId(categoryComboBox) + ", " + discount + ", " + quantity + ", " + AppHelper.SqlText(descriptionTextBox.Text) + ", " + AppHelper.SqlText(photoPath) + ")"; DatabaseHelper.ExecuteCommand(sql); } 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 string SaveSelectedImage(string article) { if (string.IsNullOrWhiteSpace(selectedImagePath)) { return oldPhotoPath; } string imagesDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images"); Directory.CreateDirectory(imagesDirectory); string safeArticle = article; foreach (char invalidChar in Path.GetInvalidFileNameChars()) { safeArticle = safeArticle.Replace(invalidChar, '_'); } string fileName = safeArticle + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg"; string destinationPath = Path.Combine(imagesDirectory, fileName); using (Image source = Image.FromFile(selectedImagePath)) { using (Bitmap resized = new Bitmap(300, 200)) { using (Graphics 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 { DataTable table = DatabaseHelper.GetData("SELECT COUNT(*) AS CountItems FROM dbo.OrderItems WHERE ProductId = " + productId); int countItems = Convert.ToInt32(table.Rows[0]["CountItems"]); if (countItems > 0) { AppHelper.ShowError("Товар присутствует в заказе. Удаление запрещено."); return; } DialogResult result = MessageBox.Show( "Удалить выбранный товар?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result != DialogResult.Yes) { 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 void DeleteOldPhoto(string photoPath) { if (string.IsNullOrWhiteSpace(photoPath)) { return; } string fullPath = Path.GetFullPath(AppHelper.GetFilePath(photoPath)); string imagesDirectory = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images")); string 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); } } }