Загрузка данных
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace TicketSales
{
public partial class Form1 : Form
{
private string connectionString =
“Server=localhost;Database=ticket_sales;Uid=root;Pwd=YOUR_PASSWORD;SslMode=None;”;
private DataGridView eventsGrid;
private TextBox customerTextBox;
private NumericUpDown quantityNumeric;
private Button loadButton;
private Button bookButton;
private Label statusLabel;
public Form1()
{
BuildWindow();
LoadEvents();
}
private void BuildWindow()
{
Text = "Продажа билетов на мероприятия";
Size = new Size(950, 600);
StartPosition = FormStartPosition.CenterScreen;
MinimumSize = new Size(750, 450);
Label titleLabel = new Label();
titleLabel.Text = "Продажа билетов на мероприятия";
titleLabel.Font = new Font("Arial", 18, FontStyle.Bold);
titleLabel.Location = new Point(20, 15);
titleLabel.Size = new Size(600, 35);
Controls.Add(titleLabel);
eventsGrid = new DataGridView();
eventsGrid.Location = new Point(20, 65);
eventsGrid.Size = new Size(890, 300);
eventsGrid.Anchor = AnchorStyles.Top |
AnchorStyles.Bottom |
AnchorStyles.Left |
AnchorStyles.Right;
eventsGrid.ReadOnly = true;
eventsGrid.AllowUserToAddRows = false;
eventsGrid.SelectionMode =
DataGridViewSelectionMode.FullRowSelect;
eventsGrid.MultiSelect = false;
eventsGrid.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.Fill;
Controls.Add(eventsGrid);
Label customerLabel = new Label();
customerLabel.Text = "ФИО покупателя:";
customerLabel.Location = new Point(20, 385);
customerLabel.Size = new Size(150, 25);
Controls.Add(customerLabel);
customerTextBox = new TextBox();
customerTextBox.Location = new Point(170, 382);
customerTextBox.Size = new Size(300, 25);
Controls.Add(customerTextBox);
Label quantityLabel = new Label();
quantityLabel.Text = "Количество билетов:";
quantityLabel.Location = new Point(20, 425);
quantityLabel.Size = new Size(150, 25);
Controls.Add(quantityLabel);
quantityNumeric = new NumericUpDown();
quantityNumeric.Location = new Point(170, 422);
quantityNumeric.Minimum = 1;
quantityNumeric.Maximum = 20;
quantityNumeric.Value = 1;
Controls.Add(quantityNumeric);
loadButton = new Button();
loadButton.Text = "Обновить мероприятия";
loadButton.Location = new Point(500, 382);
loadButton.Size = new Size(200, 35);
loadButton.Click += LoadButton_Click;
Controls.Add(loadButton);
bookButton = new Button();
bookButton.Text = "Купить билеты";
bookButton.Location = new Point(500, 422);
bookButton.Size = new Size(200, 35);
bookButton.Click += BookButton_Click;
Controls.Add(bookButton);
statusLabel = new Label();
statusLabel.Text = "Выберите мероприятие из списка.";
statusLabel.Location = new Point(20, 480);
statusLabel.Size = new Size(850, 35);
statusLabel.Anchor = AnchorStyles.Bottom |
AnchorStyles.Left |
AnchorStyles.Right;
Controls.Add(statusLabel);
}
private void LoadButton_Click(object sender, EventArgs e)
{
LoadEvents();
}
private void LoadEvents()
{
try
{
using (MySqlConnection connection =
new MySqlConnection(connectionString))
{
connection.Open();
string query =
"SELECT id AS 'Номер', " +
"name AS 'Мероприятие', " +
"event_date AS 'Дата', " +
"place AS 'Место проведения', " +
"price AS 'Цена билета' " +
"FROM Events ORDER BY event_date;";
using (MySqlDataAdapter adapter =
new MySqlDataAdapter(query, connection))
{
DataTable table = new DataTable();
adapter.Fill(table);
eventsGrid.DataSource = table;
}
}
statusLabel.Text = "Список мероприятий загружен.";
}
catch (Exception ex)
{
statusLabel.Text = "Не удалось загрузить мероприятия.";
MessageBox.Show(
"Ошибка подключения или загрузки данных:\n" +
ex.Message,
"Ошибка",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void BookButton_Click(object sender, EventArgs e)
{
if (eventsGrid.CurrentRow == null)
{
MessageBox.Show("Сначала выберите мероприятие.");
return;
}
string customerName = customerTextBox.Text.Trim();
if (customerName.Length == 0)
{
MessageBox.Show("Введите ФИО покупателя.");
return;
}
int eventId = Convert.ToInt32(
eventsGrid.CurrentRow.Cells["Номер"].Value);
int quantity = Convert.ToInt32(quantityNumeric.Value);
try
{
using (MySqlConnection connection =
new MySqlConnection(connectionString))
{
connection.Open();
string priceQuery =
"SELECT price FROM Events WHERE id = @eventId;";
decimal price;
using (MySqlCommand priceCommand =
new MySqlCommand(priceQuery, connection))
{
priceCommand.Parameters.AddWithValue(
"@eventId", eventId);
object result = priceCommand.ExecuteScalar();
if (result == null || result == DBNull.Value)
{
MessageBox.Show("Мероприятие не найдено.");
return;
}
price = Convert.ToDecimal(result);
}
decimal totalPrice = price * quantity;
string insertQuery =
"INSERT INTO Orders " +
"(event_id, customer_name, quantity, total_price) " +
"VALUES (@eventId, @customer, @quantity, @total);";
using (MySqlCommand command =
new MySqlCommand(insertQuery, connection))
{
command.Parameters.AddWithValue(
"@eventId", eventId);
command.Parameters.AddWithValue(
"@customer", customerName);
command.Parameters.AddWithValue(
"@quantity", quantity);
command.Parameters.AddWithValue(
"@total", totalPrice);
command.ExecuteNonQuery();
}
MessageBox.Show(
"Покупка оформлена!\n" +
"Покупатель: " + customerName + "\n" +
"Количество билетов: " + quantity + "\n" +
"Общая стоимость: " +
totalPrice.ToString("0.00") + " руб.",
"Покупка билетов",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
statusLabel.Text = "Покупка успешно оформлена.";
customerTextBox.Clear();
quantityNumeric.Value = 1;
}
}
catch (Exception ex)
{
MessageBox.Show(
"Не удалось оформить покупку:\n" + ex.Message,
"Ошибка",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}