From ecfb44003c70fa7c112fd9f1ea855f26728d682e Mon Sep 17 00:00:00 2001 From: Timourka Date: Wed, 27 Mar 2024 03:08:15 +0400 Subject: [PATCH] =?UTF-8?q?=D1=83=D1=80=D0=B0=20=D0=B2=D1=81=D1=91=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=D0=B5=D1=82,=20=D0=B2?= =?UTF-8?q?=D0=BE=20=D0=B2=D1=81=D0=B5=D1=85=20=D1=84=D0=BE=D1=80=D0=BC?= =?UTF-8?q?=D0=B0=D1=85=20=D1=80=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B0=20=D0=BB=D0=BE=D0=B3=D0=B8=D0=BA=D0=B0,=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=20=D1=81=20=D0=B1=D0=B0?= =?UTF-8?q?=D0=B7=D0=BE=D0=B9=20=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D1=82=D0=BE=D0=B6=D0=B5=20=D0=BF=D0=BE=D1=80=D0=B5=D0=B4=D0=B0?= =?UTF-8?q?=D1=87=D0=B8=D0=BB=D0=B0=D1=81=D1=8C=20=D1=87=D1=82=D0=BE=20?= =?UTF-8?q?=D0=B1=D1=8B=20=D0=BD=D0=B5=20=D0=B1=D1=8B=D0=BB=D0=BE=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B1=D0=BB=D0=B5=D0=BC=20=D1=81=20=D0=B4=D0=B0?= =?UTF-8?q?=D1=82=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SUBD_Car_rent/Forms/FormBranch.Designer.cs | 5 + SUBD_Car_rent/Forms/FormBranch.cs | 118 +++++++++++++++- SUBD_Car_rent/Forms/FormCar.Designer.cs | 97 +++++++------ SUBD_Car_rent/Forms/FormCar.cs | 152 ++++++++++++++++++++- SUBD_Car_rent/Forms/FormClient.Designer.cs | 33 +++-- SUBD_Car_rent/Forms/FormClient.cs | 107 ++++++++++++++- SUBD_Car_rent/Forms/FormMain.Designer.cs | 14 +- SUBD_Car_rent/Forms/FormRental.Designer.cs | 17 ++- SUBD_Car_rent/Forms/FormRental.cs | 151 +++++++++++++++++++- SUBD_Car_rent/database/Implementation.cs | 48 +++++-- SUBD_Car_rent/database/models.cs | 6 + 11 files changed, 656 insertions(+), 92 deletions(-) diff --git a/SUBD_Car_rent/Forms/FormBranch.Designer.cs b/SUBD_Car_rent/Forms/FormBranch.Designer.cs index ee9cae3..45bf7f9 100644 --- a/SUBD_Car_rent/Forms/FormBranch.Designer.cs +++ b/SUBD_Car_rent/Forms/FormBranch.Designer.cs @@ -51,6 +51,7 @@ buttonDelete.TabIndex = 28; buttonDelete.Text = "delete"; buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; // // buttonUpdate // @@ -60,6 +61,7 @@ buttonUpdate.TabIndex = 27; buttonUpdate.Text = "update"; buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; // // buttonCreate // @@ -69,6 +71,7 @@ buttonCreate.TabIndex = 26; buttonCreate.Text = "create"; buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += buttonCreate_Click; // // textBoxName // @@ -122,6 +125,7 @@ dataGridView.RowTemplate.Height = 25; dataGridView.Size = new Size(579, 426); dataGridView.TabIndex = 15; + dataGridView.CellClick += dataGridView_CellClick; // // textBoxAddress // @@ -163,6 +167,7 @@ Controls.Add(dataGridView); Name = "FormBranch"; Text = "FormBranch"; + Load += FormBranch_Load; ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); PerformLayout(); diff --git a/SUBD_Car_rent/Forms/FormBranch.cs b/SUBD_Car_rent/Forms/FormBranch.cs index d8c3ec2..d5cd364 100644 --- a/SUBD_Car_rent/Forms/FormBranch.cs +++ b/SUBD_Car_rent/Forms/FormBranch.cs @@ -1,4 +1,5 @@ -using System; +using database; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -12,9 +13,122 @@ namespace Forms { public partial class FormBranch : Form { - public FormBranch() + private Abstractions bd; + public FormBranch(Abstractions _bd) { InitializeComponent(); + bd = _bd; + } + private void loadData() + { + // Получаем список филиалов + List branches = bd.GetBranches(); + + // Очищаем dataGridView перед заполнением новыми данными + dataGridView.Rows.Clear(); + + // Предварительно определяем столбцы, если это не было сделано ранее + if (dataGridView.ColumnCount == 0) + { + dataGridView.Columns.Add("Id", "ID"); + dataGridView.Columns.Add("Name", "Name"); + dataGridView.Columns.Add("Address", "Address"); + dataGridView.Columns.Add("Phone", "Phone"); + dataGridView.Columns.Add("WorkingHours", "Working Hours"); + } + + // Заполняем dataGridView данными из списка филиалов + foreach (Branch branch in branches) + { + dataGridView.Rows.Add(branch.Id, branch.Name, branch.Address, branch.Phone, branch.WorkingHours); + } + + } + + private void buttonCreate_Click(object sender, EventArgs e) + { + // Создаем новый объект Branch и заполняем его данными из текстовых полей + Branch newBranch = new Branch + { + Name = textBoxName.Text, + Address = textBoxAddress.Text, + Phone = textBoxPhone.Text, + WorkingHours = textBoxWorkingHours.Text + }; + + // Вызываем метод добавления нового филиала в базу данных + bd.AddBranch(newBranch); + + // Перезагружаем данные в dataGridView + loadData(); + } + + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count > 0) + { + // Получаем выбранный филиал из dataGridView + DataGridViewRow selectedRow = dataGridView.SelectedRows[0]; + int branchId = Convert.ToInt32(selectedRow.Cells["Id"].Value); + + // Создаем объект Branch с обновленными данными из текстовых полей + Branch updatedBranch = new Branch + { + Id = branchId, + Name = textBoxName.Text, + Address = textBoxAddress.Text, + Phone = textBoxPhone.Text, + WorkingHours = textBoxWorkingHours.Text + }; + + // Вызываем метод обновления филиала в базе данных + bd.UpdateBranch(updatedBranch); + + // Перезагружаем данные в dataGridView + loadData(); + } + else + { + MessageBox.Show("Please select a branch to update."); + } + } + + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count > 0) + { + // Получаем выбранный филиал из dataGridView + DataGridViewRow selectedRow = dataGridView.SelectedRows[0]; + int branchId = Convert.ToInt32(selectedRow.Cells["Id"].Value); + + // Вызываем метод удаления филиала из базы данных + bd.DeleteBranch(branchId); + + // Перезагружаем данные в dataGridView + loadData(); + } + else + { + MessageBox.Show("Please select a branch to delete."); + } + } + + private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e) + { + if (e.RowIndex >= 0) + { + DataGridViewRow row = dataGridView.Rows[e.RowIndex]; + + textBoxName.Text = row.Cells["Name"].Value.ToString(); + textBoxAddress.Text = row.Cells["Address"].Value.ToString(); + textBoxPhone.Text = row.Cells["Phone"].Value.ToString(); + textBoxWorkingHours.Text = row.Cells["WorkingHours"].Value.ToString(); + } + } + + private void FormBranch_Load(object sender, EventArgs e) + { + loadData(); } } } diff --git a/SUBD_Car_rent/Forms/FormCar.Designer.cs b/SUBD_Car_rent/Forms/FormCar.Designer.cs index 8f74c70..c89f9eb 100644 --- a/SUBD_Car_rent/Forms/FormCar.Designer.cs +++ b/SUBD_Car_rent/Forms/FormCar.Designer.cs @@ -31,17 +31,17 @@ buttonDelete = new Button(); buttonUpdate = new Button(); buttonCreate = new Button(); - comboBoxBodyType = new ComboBox(); - textBoxSeats = new TextBox(); + comboBoxModel = new ComboBox(); textBoxYear = new TextBox(); - textBoxModel = new TextBox(); - textBoxBrand = new TextBox(); + textBoxMileage = new TextBox(); label5 = new Label(); label4 = new Label(); label3 = new Label(); label2 = new Label(); label1 = new Label(); dataGridView = new DataGridView(); + comboBoxBranch = new ComboBox(); + comboBoxStatus = new ComboBox(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); // @@ -53,6 +53,7 @@ buttonDelete.TabIndex = 28; buttonDelete.Text = "delete"; buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; // // buttonUpdate // @@ -62,6 +63,7 @@ buttonUpdate.TabIndex = 27; buttonUpdate.Text = "update"; buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; // // buttonCreate // @@ -71,21 +73,15 @@ buttonCreate.TabIndex = 26; buttonCreate.Text = "create"; buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += buttonCreate_Click; // - // comboBoxBodyType + // comboBoxModel // - comboBoxBodyType.FormattingEnabled = true; - comboBoxBodyType.Location = new Point(688, 98); - comboBoxBodyType.Name = "comboBoxBodyType"; - comboBoxBodyType.Size = new Size(100, 23); - comboBoxBodyType.TabIndex = 25; - // - // textBoxSeats - // - textBoxSeats.Location = new Point(688, 127); - textBoxSeats.Name = "textBoxSeats"; - textBoxSeats.Size = new Size(100, 23); - textBoxSeats.TabIndex = 24; + comboBoxModel.FormattingEnabled = true; + comboBoxModel.Location = new Point(688, 11); + comboBoxModel.Name = "comboBoxModel"; + comboBoxModel.Size = new Size(100, 23); + comboBoxModel.TabIndex = 25; // // textBoxYear // @@ -94,37 +90,30 @@ textBoxYear.Size = new Size(100, 23); textBoxYear.TabIndex = 23; // - // textBoxModel + // textBoxMileage // - textBoxModel.Location = new Point(688, 40); - textBoxModel.Name = "textBoxModel"; - textBoxModel.Size = new Size(100, 23); - textBoxModel.TabIndex = 22; - // - // textBoxBrand - // - textBoxBrand.Location = new Point(688, 11); - textBoxBrand.Name = "textBoxBrand"; - textBoxBrand.Size = new Size(100, 23); - textBoxBrand.TabIndex = 21; + textBoxMileage.Location = new Point(688, 98); + textBoxMileage.Name = "textBoxMileage"; + textBoxMileage.Size = new Size(100, 23); + textBoxMileage.TabIndex = 21; // // label5 // label5.AutoSize = true; label5.Location = new Point(622, 130); label5.Name = "label5"; - label5.Size = new Size(34, 15); + label5.Size = new Size(39, 15); label5.TabIndex = 20; - label5.Text = "Seats"; + label5.Text = "Status"; // // label4 // label4.AutoSize = true; label4.Location = new Point(622, 101); label4.Name = "label4"; - label4.Size = new Size(60, 15); + label4.Size = new Size(49, 15); label4.TabIndex = 19; - label4.Text = "Body type"; + label4.Text = "Mileage"; // // label3 // @@ -140,18 +129,18 @@ label2.AutoSize = true; label2.Location = new Point(622, 43); label2.Name = "label2"; - label2.Size = new Size(41, 15); + label2.Size = new Size(44, 15); label2.TabIndex = 17; - label2.Text = "Model"; + label2.Text = "Branch"; // // label1 // label1.AutoSize = true; label1.Location = new Point(622, 14); label1.Name = "label1"; - label1.Size = new Size(38, 15); + label1.Size = new Size(41, 15); label1.TabIndex = 16; - label1.Text = "Brand"; + label1.Text = "Model"; // // dataGridView // @@ -162,20 +151,37 @@ dataGridView.RowTemplate.Height = 25; dataGridView.Size = new Size(603, 426); dataGridView.TabIndex = 15; + dataGridView.CellClick += dataGridView_CellClick; + // + // comboBoxBranch + // + comboBoxBranch.FormattingEnabled = true; + comboBoxBranch.Location = new Point(688, 40); + comboBoxBranch.Name = "comboBoxBranch"; + comboBoxBranch.Size = new Size(100, 23); + comboBoxBranch.TabIndex = 29; + // + // comboBoxStatus + // + comboBoxStatus.FormattingEnabled = true; + comboBoxStatus.Location = new Point(688, 127); + comboBoxStatus.Name = "comboBoxStatus"; + comboBoxStatus.Size = new Size(100, 23); + comboBoxStatus.TabIndex = 30; // // FormCar // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); + Controls.Add(comboBoxStatus); + Controls.Add(comboBoxBranch); Controls.Add(buttonDelete); Controls.Add(buttonUpdate); Controls.Add(buttonCreate); - Controls.Add(comboBoxBodyType); - Controls.Add(textBoxSeats); + Controls.Add(comboBoxModel); Controls.Add(textBoxYear); - Controls.Add(textBoxModel); - Controls.Add(textBoxBrand); + Controls.Add(textBoxMileage); Controls.Add(label5); Controls.Add(label4); Controls.Add(label3); @@ -184,6 +190,7 @@ Controls.Add(dataGridView); Name = "FormCar"; Text = "FormCar"; + Load += FormCar_Load; ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); PerformLayout(); @@ -194,16 +201,16 @@ private Button buttonDelete; private Button buttonUpdate; private Button buttonCreate; - private ComboBox comboBoxBodyType; - private TextBox textBoxSeats; + private ComboBox comboBoxModel; private TextBox textBoxYear; - private TextBox textBoxModel; - private TextBox textBoxBrand; + private TextBox textBoxMileage; private Label label5; private Label label4; private Label label3; private Label label2; private Label label1; private DataGridView dataGridView; + private ComboBox comboBoxBranch; + private ComboBox comboBoxStatus; } } \ No newline at end of file diff --git a/SUBD_Car_rent/Forms/FormCar.cs b/SUBD_Car_rent/Forms/FormCar.cs index 5cb25a1..aa5d9a7 100644 --- a/SUBD_Car_rent/Forms/FormCar.cs +++ b/SUBD_Car_rent/Forms/FormCar.cs @@ -1,4 +1,5 @@ -using System; +using database; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -12,9 +13,156 @@ namespace Forms { public partial class FormCar : Form { - public FormCar() + private Abstractions bd; + public FormCar(Abstractions _bd) { InitializeComponent(); + bd = _bd; + } + private void loadData() + { + // Получаем список автомобилей + List cars = bd.GetCars(); + + // Очищаем dataGridView перед заполнением новыми данными + dataGridView.Rows.Clear(); + + // Предварительно определяем столбцы, если это не было сделано ранее + if (dataGridView.ColumnCount == 0) + { + dataGridView.Columns.Add("Id", "ID"); + dataGridView.Columns.Add("ModelId", "ModelId"); + dataGridView.Columns["ModelId"].Visible = false; + dataGridView.Columns.Add("Model", "Model"); + dataGridView.Columns.Add("BranchId", "BranchId"); + dataGridView.Columns["BranchId"].Visible = false; + dataGridView.Columns.Add("Branch", "Branch"); + dataGridView.Columns.Add("Year", "Year"); + dataGridView.Columns.Add("Mileage", "Mileage"); + dataGridView.Columns.Add("StatusId", "StatusId"); + dataGridView.Columns["StatusId"].Visible = false; + dataGridView.Columns.Add("Status", "Status"); + } + + // Заполняем dataGridView данными из списка автомобилей + foreach (Car car in cars) + { + dataGridView.Rows.Add(car.Id, + car.ModelId, + bd.GetCarModelById(car.ModelId).Brand + " " + bd.GetCarModelById(car.ModelId).Model, + car.BranchId, + bd.GetBranchById(car.BranchId).Name, + car.Year, car.Mileage, + car.StatusId, + bd.GetStatusById(car.StatusId).Title); + } + + } + private void buttonCreate_Click(object sender, EventArgs e) + { + // Создаем новый объект Car и заполняем его данными из текстовых полей и комбо-боксов + Car newCar = new Car + { + Mileage = int.Parse(textBoxMileage.Text), + Year = int.Parse(textBoxYear.Text), + BranchId = ((Branch)comboBoxBranch.SelectedItem).Id, + ModelId = ((helpCombobox)comboBoxModel.SelectedItem).Id, + StatusId = ((Status)comboBoxStatus.SelectedItem).Id + }; + + // Вызываем метод добавления нового автомобиля в базу данных + bd.AddCar(newCar); + + // Обновляем dataGridView + loadData(); + } + + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count > 0) + { + // Получаем индекс выбранной строки + int rowIndex = dataGridView.CurrentCell.RowIndex; + + // Получаем ID редактируемого автомобиля из выбранной строки dataGridView + int carId = (int)dataGridView.Rows[rowIndex].Cells["Id"].Value; + + // Создаем объект Car и заполняем его данными из текстовых полей и комбо-боксов + Car updatedCar = new Car + { + Id = carId, + Mileage = int.Parse(textBoxMileage.Text), + Year = int.Parse(textBoxYear.Text), + BranchId = ((Branch)comboBoxBranch.SelectedItem).Id, + ModelId = ((helpCombobox)comboBoxModel.SelectedItem).Id, + StatusId = ((Status)comboBoxStatus.SelectedItem).Id + }; + + // Вызываем метод обновления автомобиля в базе данных + bd.UpdateCar(updatedCar); + + // Обновляем dataGridView + loadData(); + } + } + + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count > 0) + { + // Получаем индекс выбранной строки + int rowIndex = dataGridView.CurrentCell.RowIndex; + + // Получаем ID удаляемого автомобиля из выбранной строки dataGridView + int carId = (int)dataGridView.Rows[rowIndex].Cells["Id"].Value; + + // Вызываем метод удаления автомобиля из базы данных + bd.DeleteCar(carId); + + // Обновляем dataGridView + loadData(); + } + } + + private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e) + { + if (e.RowIndex >= 0) + { + DataGridViewRow row = dataGridView.Rows[e.RowIndex]; + + // Заполняем текстовые поля данными из выбранной строки + textBoxMileage.Text = row.Cells["Mileage"].Value.ToString(); + textBoxYear.Text = row.Cells["Year"].Value.ToString(); + + // Получаем значения для комбо-боксов из выбранной строки + int branchId = Convert.ToInt32(row.Cells["BranchId"].Value); + int modelId = Convert.ToInt32(row.Cells["ModelId"].Value); + int statusId = Convert.ToInt32(row.Cells["StatusId"].Value); + + // Заполняем комбо-боксы данными из БД + comboBoxBranch.DataSource = bd.GetBranches(); + comboBoxBranch.DisplayMember = "Name"; + comboBoxBranch.ValueMember = "Id"; + comboBoxBranch.SelectedValue = branchId; + + comboBoxModel.DataSource = bd.GetCarModels() + .Select(x => new helpCombobox() { + Text = x.Brand + " " + x.Model, + Id = x.Id }).ToList(); + comboBoxModel.DisplayMember = "Text"; + comboBoxModel.ValueMember = "Id"; + comboBoxModel.SelectedValue = modelId; + + comboBoxStatus.DataSource = bd.GetStatuses(); + comboBoxStatus.DisplayMember = "Title"; + comboBoxStatus.ValueMember = "Id"; + comboBoxStatus.SelectedValue = statusId; + } + } + + private void FormCar_Load(object sender, EventArgs e) + { + loadData(); } } } diff --git a/SUBD_Car_rent/Forms/FormClient.Designer.cs b/SUBD_Car_rent/Forms/FormClient.Designer.cs index 3093033..4e82c95 100644 --- a/SUBD_Car_rent/Forms/FormClient.Designer.cs +++ b/SUBD_Car_rent/Forms/FormClient.Designer.cs @@ -32,8 +32,8 @@ buttonUpdate = new Button(); buttonCreate = new Button(); textBoxEmail = new TextBox(); - this.textBoxAdress = new TextBox(); - this.textBoxSurname = new TextBox(); + textBoxAddress = new TextBox(); + textBoxSurname = new TextBox(); textBoxName = new TextBox(); label5 = new Label(); label4 = new Label(); @@ -53,6 +53,7 @@ buttonDelete.TabIndex = 28; buttonDelete.Text = "delete"; buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; // // buttonUpdate // @@ -62,6 +63,7 @@ buttonUpdate.TabIndex = 27; buttonUpdate.Text = "update"; buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; // // buttonCreate // @@ -71,6 +73,7 @@ buttonCreate.TabIndex = 26; buttonCreate.Text = "create"; buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += buttonCreate_Click; // // textBoxEmail // @@ -79,19 +82,19 @@ textBoxEmail.Size = new Size(100, 23); textBoxEmail.TabIndex = 24; // - // textBoxAdress + // textBoxAddress // - this.textBoxAdress.Location = new Point(688, 69); - this.textBoxAdress.Name = "textBoxAdress"; - this.textBoxAdress.Size = new Size(100, 23); - this.textBoxAdress.TabIndex = 23; + textBoxAddress.Location = new Point(688, 69); + textBoxAddress.Name = "textBoxAddress"; + textBoxAddress.Size = new Size(100, 23); + textBoxAddress.TabIndex = 23; // // textBoxSurname // - this.textBoxSurname.Location = new Point(688, 40); - this.textBoxSurname.Name = "textBoxSurname"; - this.textBoxSurname.Size = new Size(100, 23); - this.textBoxSurname.TabIndex = 22; + textBoxSurname.Location = new Point(688, 40); + textBoxSurname.Name = "textBoxSurname"; + textBoxSurname.Size = new Size(100, 23); + textBoxSurname.TabIndex = 22; // // textBoxName // @@ -154,6 +157,7 @@ dataGridView.RowTemplate.Height = 25; dataGridView.Size = new Size(603, 426); dataGridView.TabIndex = 15; + dataGridView.CellClick += dataGridView_CellClick; // // textBoxPhone // @@ -172,8 +176,8 @@ Controls.Add(buttonUpdate); Controls.Add(buttonCreate); Controls.Add(textBoxEmail); - Controls.Add(this.textBoxAdress); - Controls.Add(this.textBoxSurname); + Controls.Add(textBoxAddress); + Controls.Add(textBoxSurname); Controls.Add(textBoxName); Controls.Add(label5); Controls.Add(label4); @@ -183,6 +187,7 @@ Controls.Add(dataGridView); Name = "FormClient"; Text = "FormClient"; + Load += FormClient_Load; ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); PerformLayout(); @@ -194,7 +199,7 @@ private Button buttonUpdate; private Button buttonCreate; private TextBox textBoxEmail; - private TextBox textBoxAdress; + private TextBox textBoxAddress; private TextBox textBoxSurname; private TextBox textBoxName; private TextBox textBoxPhone; diff --git a/SUBD_Car_rent/Forms/FormClient.cs b/SUBD_Car_rent/Forms/FormClient.cs index d36a605..9c66719 100644 --- a/SUBD_Car_rent/Forms/FormClient.cs +++ b/SUBD_Car_rent/Forms/FormClient.cs @@ -1,4 +1,5 @@ -using System; +using database; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -12,9 +13,111 @@ namespace Forms { public partial class FormClient : Form { - public FormClient() + private Abstractions bd; + public FormClient(Abstractions _bd) { InitializeComponent(); + bd = _bd; + } + private void loadData() + { + // Получаем список клиентов + List clients = bd.GetClients(); + + // Очищаем dataGridView перед заполнением новыми данными + dataGridView.Rows.Clear(); + + // Предварительно определяем столбцы, если это не было сделано ранее + if (dataGridView.ColumnCount == 0) + { + dataGridView.Columns.Add("Id", "ID"); + dataGridView.Columns.Add("Name", "Name"); + dataGridView.Columns.Add("Surname", "Surname"); + dataGridView.Columns.Add("Address", "Address"); + dataGridView.Columns.Add("Phone", "Phone"); + dataGridView.Columns.Add("Email", "Email"); + } + + // Заполняем dataGridView данными из списка клиентов + foreach (Client client in clients) + { + dataGridView.Rows.Add(client.Id, client.Name, client.Surname, client.Address, client.Phone, client.Email); + } + + } + + // Создание новой записи клиента + private void buttonCreate_Click(object sender, EventArgs e) + { + Client newClient = new Client + { + Name = textBoxName.Text, + Surname = textBoxSurname.Text, + Address = textBoxAddress.Text, + Phone = textBoxPhone.Text, + Email = textBoxEmail.Text + }; + + bd.AddClient(newClient); + // Обновляем отображение данных + loadData(); + } + + // Обновление выбранной записи клиента + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count > 0) + { + DataGridViewRow row = dataGridView.SelectedRows[0]; + int clientId = Convert.ToInt32(row.Cells["Id"].Value); + + Client updatedClient = new Client + { + Id = clientId, + Name = textBoxName.Text, + Surname = textBoxSurname.Text, + Address = textBoxAddress.Text, + Phone = textBoxPhone.Text, + Email = textBoxEmail.Text + }; + + bd.UpdateClient(updatedClient); + // Обновляем отображение данных + loadData(); + } + } + + // Удаление выбранной записи клиента + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count > 0) + { + DataGridViewRow row = dataGridView.SelectedRows[0]; + int clientId = Convert.ToInt32(row.Cells["Id"].Value); + + bd.DeleteClient(clientId); + // Обновляем отображение данных + loadData(); + } + } + + private void FormClient_Load(object sender, EventArgs e) + { + loadData(); + } + + private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e) + { + if (e.RowIndex >= 0) + { + DataGridViewRow row = dataGridView.Rows[e.RowIndex]; + + textBoxName.Text = row.Cells["Name"].Value.ToString(); + textBoxSurname.Text = row.Cells["Surname"].Value.ToString(); + textBoxAddress.Text = row.Cells["Address"].Value.ToString(); + textBoxPhone.Text = row.Cells["Phone"].Value.ToString(); + textBoxEmail.Text = row.Cells["Email"].Value.ToString(); + } } } } diff --git a/SUBD_Car_rent/Forms/FormMain.Designer.cs b/SUBD_Car_rent/Forms/FormMain.Designer.cs index f2f3772..7017f5d 100644 --- a/SUBD_Car_rent/Forms/FormMain.Designer.cs +++ b/SUBD_Car_rent/Forms/FormMain.Designer.cs @@ -43,7 +43,7 @@ menuStrip1.Items.AddRange(new ToolStripItem[] { tablesToolStripMenuItem }); menuStrip1.Location = new Point(0, 0); menuStrip1.Name = "menuStrip1"; - menuStrip1.Size = new Size(800, 24); + menuStrip1.Size = new Size(435, 24); menuStrip1.TabIndex = 0; menuStrip1.Text = "menuStrip1"; // @@ -57,35 +57,35 @@ // carModelToolStripMenuItem // carModelToolStripMenuItem.Name = "carModelToolStripMenuItem"; - carModelToolStripMenuItem.Size = new Size(180, 22); + carModelToolStripMenuItem.Size = new Size(127, 22); carModelToolStripMenuItem.Text = "car model"; carModelToolStripMenuItem.Click += carModelToolStripMenuItem_Click; // // carToolStripMenuItem // carToolStripMenuItem.Name = "carToolStripMenuItem"; - carToolStripMenuItem.Size = new Size(180, 22); + carToolStripMenuItem.Size = new Size(127, 22); carToolStripMenuItem.Text = "car"; carToolStripMenuItem.Click += carToolStripMenuItem_Click; // // branchToolStripMenuItem // branchToolStripMenuItem.Name = "branchToolStripMenuItem"; - branchToolStripMenuItem.Size = new Size(180, 22); + branchToolStripMenuItem.Size = new Size(127, 22); branchToolStripMenuItem.Text = "branch"; branchToolStripMenuItem.Click += branchToolStripMenuItem_Click; // // clientToolStripMenuItem // clientToolStripMenuItem.Name = "clientToolStripMenuItem"; - clientToolStripMenuItem.Size = new Size(180, 22); + clientToolStripMenuItem.Size = new Size(127, 22); clientToolStripMenuItem.Text = "client"; clientToolStripMenuItem.Click += clientToolStripMenuItem_Click; // // rentalToolStripMenuItem // rentalToolStripMenuItem.Name = "rentalToolStripMenuItem"; - rentalToolStripMenuItem.Size = new Size(180, 22); + rentalToolStripMenuItem.Size = new Size(127, 22); rentalToolStripMenuItem.Text = "rental"; rentalToolStripMenuItem.Click += rentalToolStripMenuItem_Click; // @@ -93,7 +93,7 @@ // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); + ClientSize = new Size(435, 167); Controls.Add(menuStrip1); MainMenuStrip = menuStrip1; Name = "FormMain"; diff --git a/SUBD_Car_rent/Forms/FormRental.Designer.cs b/SUBD_Car_rent/Forms/FormRental.Designer.cs index b5ee5d8..cd79a90 100644 --- a/SUBD_Car_rent/Forms/FormRental.Designer.cs +++ b/SUBD_Car_rent/Forms/FormRental.Designer.cs @@ -53,6 +53,7 @@ buttonDelete.TabIndex = 28; buttonDelete.Text = "delete"; buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; // // buttonUpdate // @@ -62,6 +63,7 @@ buttonUpdate.TabIndex = 27; buttonUpdate.Text = "update"; buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; // // buttonCreate // @@ -71,34 +73,35 @@ buttonCreate.TabIndex = 26; buttonCreate.Text = "create"; buttonCreate.UseVisualStyleBackColor = true; + buttonCreate.Click += buttonCreate_Click; // // comboBoxCar // comboBoxCar.FormattingEnabled = true; comboBoxCar.Location = new Point(688, 11); comboBoxCar.Name = "comboBoxCar"; - comboBoxCar.Size = new Size(100, 23); + comboBoxCar.Size = new Size(270, 23); comboBoxCar.TabIndex = 25; // // textBoxCost // textBoxCost.Location = new Point(688, 127); textBoxCost.Name = "textBoxCost"; - textBoxCost.Size = new Size(100, 23); + textBoxCost.Size = new Size(270, 23); textBoxCost.TabIndex = 24; // // textBoxStartDate // textBoxStartDate.Location = new Point(688, 69); textBoxStartDate.Name = "textBoxStartDate"; - textBoxStartDate.Size = new Size(100, 23); + textBoxStartDate.Size = new Size(270, 23); textBoxStartDate.TabIndex = 23; // // textBoxEndDate // textBoxEndDate.Location = new Point(688, 98); textBoxEndDate.Name = "textBoxEndDate"; - textBoxEndDate.Size = new Size(100, 23); + textBoxEndDate.Size = new Size(270, 23); textBoxEndDate.TabIndex = 21; // // label5 @@ -155,20 +158,21 @@ dataGridView.RowTemplate.Height = 25; dataGridView.Size = new Size(603, 426); dataGridView.TabIndex = 15; + dataGridView.CellClick += dataGridView_CellClick; // // comboBoxClient // comboBoxClient.FormattingEnabled = true; comboBoxClient.Location = new Point(688, 40); comboBoxClient.Name = "comboBoxClient"; - comboBoxClient.Size = new Size(100, 23); + comboBoxClient.Size = new Size(270, 23); comboBoxClient.TabIndex = 29; // // FormRental // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); + ClientSize = new Size(970, 450); Controls.Add(comboBoxClient); Controls.Add(buttonDelete); Controls.Add(buttonUpdate); @@ -185,6 +189,7 @@ Controls.Add(dataGridView); Name = "FormRental"; Text = "FormRental"; + Load += FormRental_Load; ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ResumeLayout(false); PerformLayout(); diff --git a/SUBD_Car_rent/Forms/FormRental.cs b/SUBD_Car_rent/Forms/FormRental.cs index 6a6cdeb..b983f57 100644 --- a/SUBD_Car_rent/Forms/FormRental.cs +++ b/SUBD_Car_rent/Forms/FormRental.cs @@ -1,4 +1,5 @@ -using System; +using database; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -12,9 +13,155 @@ namespace Forms { public partial class FormRental : Form { - public FormRental() + private Abstractions bd; + public FormRental(Abstractions _bd) { InitializeComponent(); + bd = _bd; + } + private void loadData() + { + // Получаем список аренд + List rentals = bd.GetRentals(); + + // Очищаем dataGridView перед заполнением новыми данными + dataGridView.Rows.Clear(); + + // Предварительно определяем столбцы, если это не было сделано ранее + if (dataGridView.ColumnCount == 0) + { + dataGridView.Columns.Add("Id", "ID"); + dataGridView.Columns.Add("CarId", "CarId"); + dataGridView.Columns["CarId"].Visible = false; + dataGridView.Columns.Add("Car", "Car"); + dataGridView.Columns.Add("ClientId", "ClientId"); + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns.Add("Client", "Client"); + dataGridView.Columns.Add("StartDate", "Start Date"); + dataGridView.Columns.Add("EndDate", "End Date"); + dataGridView.Columns.Add("Cost", "Cost"); + } + + // Заполняем dataGridView данными из списка аренд + foreach (Rental rental in rentals) + { + dataGridView.Rows.Add(rental.Id, + rental.CarId, + bd.GetCarModelById(bd.GetCarById(rental.CarId).ModelId).Brand + " " + bd.GetCarModelById(bd.GetCarById(rental.CarId).ModelId).Model + " " + bd.GetCarById(rental.CarId).Year.ToString(), + rental.ClientId, + bd.GetClientById(rental.ClientId).Name + " " + bd.GetClientById(rental.ClientId).Surname, + rental.StartDate, rental.EndDate, rental.Cost); + } + + } + + private void buttonCreate_Click(object sender, EventArgs e) + { + // Создаем новый объект Rental и заполняем его данными из текстовых полей и комбо-боксов + Rental newRental = new Rental + { + Cost = decimal.Parse(textBoxCost.Text), + StartDate = DateTime.Parse(textBoxStartDate.Text), + EndDate = DateTime.Parse(textBoxEndDate.Text), + CarId = ((helpCombobox)comboBoxCar.SelectedItem).Id, + ClientId = ((helpCombobox)comboBoxClient.SelectedItem).Id + }; + + // Вызываем метод добавления новой аренды в базу данных + bd.AddRental(newRental); + + // Обновляем dataGridView + loadData(); + } + + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count > 0) + { + // Получаем индекс выбранной строки + int rowIndex = dataGridView.CurrentCell.RowIndex; + + // Получаем ID редактируемой аренды из выбранной строки dataGridView + int rentalId = (int)dataGridView.Rows[rowIndex].Cells["Id"].Value; + + // Создаем объект Rental и заполняем его данными из текстовых полей и комбо-боксов + Rental updatedRental = new Rental + { + Id = rentalId, + Cost = decimal.Parse(textBoxCost.Text), + StartDate = DateTime.Parse(textBoxStartDate.Text), + EndDate = DateTime.Parse(textBoxEndDate.Text), + CarId = ((helpCombobox)comboBoxCar.SelectedItem).Id, + ClientId = ((helpCombobox)comboBoxClient.SelectedItem).Id + }; + + // Вызываем метод обновления аренды в базе данных + bd.UpdateRental(updatedRental); + + // Обновляем dataGridView + loadData(); + } + } + + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count > 0) + { + // Получаем индекс выбранной строки + int rowIndex = dataGridView.CurrentCell.RowIndex; + + // Получаем ID удаляемой аренды из выбранной строки dataGridView + int rentalId = (int)dataGridView.Rows[rowIndex].Cells["Id"].Value; + + // Вызываем метод удаления аренды из базы данных + bd.DeleteRental(rentalId); + + // Обновляем dataGridView + loadData(); + } + } + + private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e) + { + if (e.RowIndex >= 0) + { + DataGridViewRow row = dataGridView.Rows[e.RowIndex]; + + // Заполняем текстовые поля данными из выбранной строки + textBoxCost.Text = row.Cells["Cost"].Value.ToString(); + textBoxStartDate.Text = row.Cells["StartDate"].Value.ToString(); + textBoxEndDate.Text = row.Cells["EndDate"].Value.ToString(); + + // Получаем значения для комбо-боксов из выбранной строки + int carId = Convert.ToInt32(row.Cells["CarId"].Value); + int clientId = Convert.ToInt32(row.Cells["ClientId"].Value); + + // Заполняем комбо-боксы данными из БД + comboBoxCar.DataSource = bd.GetCars() + .Select(x => new helpCombobox() + { + Text = bd.GetCarModelById(x.ModelId).Brand + " " + bd.GetCarModelById(x.ModelId).Model + " " + bd.GetStatusById(x.StatusId).Title, + Id = x.Id + }) + .ToList(); + comboBoxCar.DisplayMember = "Text"; + comboBoxCar.ValueMember = "Id"; + comboBoxCar.SelectedValue = carId; + + comboBoxClient.DataSource = bd.GetClients() + .Select(x => new helpCombobox() { + Text = x.Name + " " + x.Surname, + Id = x.Id + }).ToList(); + comboBoxClient.DisplayMember = "Text"; // Используйте свойство для отображения, например, Name или Surname + comboBoxClient.ValueMember = "Id"; + comboBoxClient.SelectedValue = clientId; + } + } + + private void FormRental_Load(object sender, EventArgs e) + { + loadData(); } } } diff --git a/SUBD_Car_rent/database/Implementation.cs b/SUBD_Car_rent/database/Implementation.cs index 03deef4..2d9f39d 100644 --- a/SUBD_Car_rent/database/Implementation.cs +++ b/SUBD_Car_rent/database/Implementation.cs @@ -16,8 +16,13 @@ namespace database { using var conn = GetConnection(); conn.Open(); - using var cmd = new NpgsqlCommand($"INSERT INTO car (model_id, branch_id, year, mileage, status_id) VALUES ({car.ModelId}, {car.BranchId}, {car.Year}, {car.Mileage}, {car.StatusId})", conn); - cmd.ExecuteNonQuery(); + using var cmd = new NpgsqlCommand("INSERT INTO car (model_id, branch_id, year, mileage, status_id) VALUES (@ModelId, @BranchId, @Year, @Mileage, @StatusId)", conn); + cmd.Parameters.AddWithValue("@ModelId", car.ModelId); + cmd.Parameters.AddWithValue("@BranchId", car.BranchId); + cmd.Parameters.AddWithValue("@Year", car.Year); + cmd.Parameters.AddWithValue("@Mileage", car.Mileage); + cmd.Parameters.AddWithValue("@StatusId", car.StatusId); + cmd.ExecuteNonQuery(); } public override List GetCars() @@ -34,9 +39,9 @@ namespace database Id = reader.GetInt32(0), ModelId = reader.GetInt32(1), BranchId = reader.GetInt32(2), - Year = reader.GetInt32(3), - Mileage = reader.GetInt32(4), - StatusId = reader.GetInt32(5) + StatusId = reader.GetInt32(3), + Year = reader.GetInt32(4), + Mileage = reader.GetInt32(5), }); } return cars; @@ -55,9 +60,9 @@ namespace database Id = reader.GetInt32(0), ModelId = reader.GetInt32(1), BranchId = reader.GetInt32(2), - Year = reader.GetInt32(3), - Mileage = reader.GetInt32(4), - StatusId = reader.GetInt32(5) + StatusId = reader.GetInt32(3), + Year = reader.GetInt32(4), + Mileage = reader.GetInt32(5), }; } return null; @@ -84,7 +89,12 @@ namespace database { using var conn = GetConnection(); conn.Open(); - using var cmd = new NpgsqlCommand($"INSERT INTO client (name, surname, address, phone, email) VALUES ('{client.Name}', '{client.Surname}', '{client.Address}', '{client.Phone}', '{client.Email}')", conn); + using var cmd = new NpgsqlCommand("INSERT INTO client (name, surname, address, phone, email) VALUES (@Name, @Surname, @Address, @Phone, @Email)", conn); + cmd.Parameters.AddWithValue("@Name", client.Name); + cmd.Parameters.AddWithValue("@Surname", client.Surname); + cmd.Parameters.AddWithValue("@Address", client.Address); + cmd.Parameters.AddWithValue("@Phone", client.Phone); + cmd.Parameters.AddWithValue("@Email", client.Email); cmd.ExecuteNonQuery(); } @@ -152,7 +162,12 @@ namespace database { using var conn = GetConnection(); conn.Open(); - using var cmd = new NpgsqlCommand($"INSERT INTO rental (car_id, client_id, start_date, end_date, cost) VALUES ({rental.CarId}, {rental.ClientId}, '{rental.StartDate}', '{rental.EndDate}', {rental.Cost})", conn); + using var cmd = new NpgsqlCommand("INSERT INTO rental (car_id, client_id, start_date, end_date, cost) VALUES (@CarId, @ClientId, @StartDate, @EndDate, @Cost)", conn); + cmd.Parameters.AddWithValue("@CarId", rental.CarId); + cmd.Parameters.AddWithValue("@ClientId", rental.ClientId); + cmd.Parameters.AddWithValue("@StartDate", rental.StartDate); + cmd.Parameters.AddWithValue("@EndDate", rental.EndDate); + cmd.Parameters.AddWithValue("@Cost", rental.Cost); cmd.ExecuteNonQuery(); } @@ -220,7 +235,12 @@ namespace database { using var conn = GetConnection(); conn.Open(); - using var cmd = new NpgsqlCommand($"INSERT INTO car_model (brand, model, year, body_type_id, seats) VALUES ('{carModel.Brand}', '{carModel.Model}', {carModel.Year}, {carModel.BodyTypeId}, {carModel.Seats})", conn); + using var cmd = new NpgsqlCommand("INSERT INTO car_model (brand, model, year, body_type_id, seats) VALUES (@Brand, @Model, @Year, @BodyTypeId, @Seats)", conn); + cmd.Parameters.AddWithValue("@Brand", carModel.Brand); + cmd.Parameters.AddWithValue("@Model", carModel.Model); + cmd.Parameters.AddWithValue("@Year", carModel.Year); + cmd.Parameters.AddWithValue("@BodyTypeId", carModel.BodyTypeId); + cmd.Parameters.AddWithValue("@Seats", carModel.Seats); cmd.ExecuteNonQuery(); } @@ -287,7 +307,11 @@ namespace database { using var conn = GetConnection(); conn.Open(); - using var cmd = new NpgsqlCommand($"INSERT INTO branch (name, address, phone, working_hours) VALUES ('{branch.Name}', '{branch.Address}', '{branch.Phone}', '{branch.WorkingHours}')", conn); + using var cmd = new NpgsqlCommand("INSERT INTO branch (name, address, phone, working_hours) VALUES (@Name, @Address, @Phone, @WorkingHours)", conn); + cmd.Parameters.AddWithValue("@Name", branch.Name); + cmd.Parameters.AddWithValue("@Address", branch.Address); + cmd.Parameters.AddWithValue("@Phone", branch.Phone); + cmd.Parameters.AddWithValue("@WorkingHours", branch.WorkingHours); cmd.ExecuteNonQuery(); } diff --git a/SUBD_Car_rent/database/models.cs b/SUBD_Car_rent/database/models.cs index 6600cee..9ee32cc 100644 --- a/SUBD_Car_rent/database/models.cs +++ b/SUBD_Car_rent/database/models.cs @@ -62,4 +62,10 @@ public int Id { get; set; } public string Title { get; set; } } + + public class helpCombobox + { + public string Text { get; set; } + public int Id { get; set; } + } }