/
DataTimeModule
/
DateTime
Обзор
Документация
Войти
/
DataTimeModule
/
DateTime
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
module2_guide.txt
216 строк
6 KB
Reeltell
upload
27 май 2026, 01:50
27 май 2026, 01:50
f282598
Код
Авторство
О чём код?
Новый Гайд По Модулю 2 1. Подготовка Создать WinForms проект. Установить NuGet: Microsoft.Data.SqlClient В проект добавить папку Images. Положить туда: Icon.png picture.png 1.jpg ... 10.jpg У картинок поставить: Copy to Output Directory = Copy if newer 2. Db.cs Создать файл Db.cs: using Microsoft.Data.SqlClient; namespace demo1; internal static class Db { private const string ConnectionString = "Data Source=localhost;Initial Catalog=demo1;Integrated Security=True;TrustServerCertificate=True"; public static SqlConnection OpenConnection() { var connection = new SqlConnection(ConnectionString); connection.Open(); return connection; } } 3. Form1 На форму входа поставить: PictureBox logoPictureBox TextBox loginTextBox TextBox passwordTextBox Button enterButton Button guestButton passwordTextBox: PasswordChar = * Кнопка входа проверяет пользователя в БД, кнопка гостя открывает товары без авторизации. Главная идея: OpenProducts(fullName, role); Для гостя: OpenProducts("Гость", "Гость"); 4. ProductForm Добавить форму ProductForm. На нее поставить: Label userLabel Button exitButton FlowLayoutPanel productsPanel У productsPanel поставить: AutoScroll = True FlowDirection = TopDown WrapContents = False Anchor = Top, Bottom, Left, Right Эта панель будет хранить карточки товаров. 5. ProductCard Добавить: Добавить -> Пользовательский элемент управления Название: ProductCard На ProductCard поставить: PictureBox photoBox Label infoLabel Label priceLabel Label discountPriceLabel Label discountLabel Пример расположения: слева photoBox; по центру infoLabel; снизу/рядом цена; справа discountLabel. Для photoBox: SizeMode = Zoom 6. Код ProductCard.cs namespace demo1 { public partial class ProductCard : UserControl { public ProductCard() { InitializeComponent(); } public void SetProduct(Image photo, string title, string category, string description, string manufacturer, string provider, decimal price, int discount, int stock, string unit) { photoBox.Image = photo; infoLabel.Text = $"{category} | {title}\n" + $"Описание товара: {description}\n" + $"Производитель: {manufacturer}\n" + $"Поставщик: {provider}\n" + $"Единица измерения: {unit}\n" + $"Количество на складе: {stock}"; priceLabel.Text = $"Цена: {price:0.00}"; discountLabel.Text = $"Скидка\n{discount}%"; if (discount > 0) { decimal newPrice = price * (100 - discount) / 100; priceLabel.ForeColor = Color.Red; priceLabel.Font = new Font(Font, FontStyle.Strikeout); discountPriceLabel.Text = $"{newPrice:0.00}"; } if (stock == 0) BackColor = Color.LightBlue; else if (discount > 15) BackColor = Color.SeaGreen; } } } 7. Код ProductForm.cs using Microsoft.Data.SqlClient; namespace demo1 { public partial class ProductForm : Form { public ProductForm(string fullName, string role) { InitializeComponent(); userLabel.Text = $"{role}: {fullName}"; } private void ProductForm_Load(object sender, EventArgs e) { LoadProducts(); } private void LoadProducts() { productsPanel.Controls.Clear(); using var connection = Db.OpenConnection(); string sql = """ SELECT p.Title, c.Title AS Category, p.Description, m.Title AS Manufacturer, pr.Title AS Provider, p.Price, p.Discount, p.StockQuantity, u.Title AS Unit, p.PhotoPath FROM Products p JOIN ProductCategories c ON p.ProductCategoryId = c.ProductCategoryId JOIN Manufacturers m ON p.ManufacturerId = m.ManufacturerId JOIN Providers pr ON p.ProviderId = pr.ProviderId JOIN Units u ON p.UnitId = u.UnitId ORDER BY p.Title """; using var command = new SqlCommand(sql, connection); using var reader = command.ExecuteReader(); while (reader.Read()) { var card = new ProductCard(); card.SetProduct( GetImage(reader["PhotoPath"].ToString()), reader["Title"].ToString()!, reader["Category"].ToString()!, reader["Description"].ToString()!, reader["Manufacturer"].ToString()!, reader["Provider"].ToString()!, Convert.ToDecimal(reader["Price"]), Convert.ToInt32(reader["Discount"]), Convert.ToInt32(reader["StockQuantity"]), reader["Unit"].ToString()!); productsPanel.Controls.Add(card); } } private Image GetImage(string? fileName) { string path = Path.Combine(AppContext.BaseDirectory, "Images", fileName?.Trim() ?? ""); if (!File.Exists(path)) path = Path.Combine(AppContext.BaseDirectory, "Images", "picture.png"); return new Bitmap(path); } private void exitButton_Click(object sender, EventArgs e) { Close(); } } }