using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using System.Drawing.Printing; namespace hospital { public partial class mainMenu : Form { SqlConnection sqlConnection = null; string query = null; SqlDataAdapter dataAdapter = null; DataSet dataSet = null; public static string index; public mainMenu() { InitializeComponent(); } private void mainMenu_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void mainMenu_Load(object sender, EventArgs e) { try { query = $"select id_card as 'ID', Surname_Patient as 'Фамилия', Name_Patient as 'Имя', Midname_Patient as 'Отчество', Date_Birthday_Patient as 'Дата рождения', Telephone_Patient as 'Телефон', IIAN_Patient as 'СНИЛС', Passport_Number_Patient as 'Серия, номер паспорта', Passport_Date_Patient as 'Дата выдачи', Passport_Place_Patient as 'Кем выдан', Passport_Code_Patient as 'Код подразделения', Number_Policy_Patient as 'Номер полиса', Disability_Patient as 'Инвалидность', Name_Blood as 'Группа крови', Name_Factor as 'Резус-фактор' from Medical_Cards join Blood_Type on Blood_Type.ID_Blood = Medical_Cards.ID_Blood join Rh_Factor on Rh_Factor.ID_Factor = Medical_Cards.ID_Factor"; FormCreating.openConnection(ref sqlConnection); dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView1.DataSource = dataSet.Tables[0]; SqlCommand a = new SqlCommand($"select name_post from posts join employees on employees.id_post = posts.id_post where id_employee like {auth.userID}", sqlConnection); if (a.ExecuteScalar().ToString().Equals("Мед-сестра")) { tabControl1.TabPages.Remove(tabPage2); delete_medicalCard.Visible = false; } } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { try { passwordFounded = false; switch (tabControl1.SelectedIndex) { case 0: query = $"select id_card as 'ID', Surname_Patient as 'Фамилия', Name_Patient as 'Имя', Midname_Patient as 'Отчество', Date_Birthday_Patient as 'Дата рождения', Telephone_Patient as 'Телефон', IIAN_Patient as 'СНИЛС', Passport_Number_Patient as 'Серия, номер паспорта', Passport_Date_Patient as 'Дата выдачи', Passport_Place_Patient as 'Кем выдан', Passport_Code_Patient as 'Код подразделения', Number_Policy_Patient as 'Номер полиса', Disability_Patient as 'Инвалидность', Name_Blood as 'Группа крови', Name_Factor as 'Резус-фактор' from Medical_Cards join Blood_Type on Blood_Type.ID_Blood = Medical_Cards.ID_Blood join Rh_Factor on Rh_Factor.ID_Factor = Medical_Cards.ID_Factor"; dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView1.DataSource = dataSet.Tables[0]; debugAndTrace.writeInFile("Включена вкладка \"Медицинские карты\""); break; case 1: query = $"select id_patientcard as 'ID', surname_patient + ' ' + Name_Patient + ' ' + Midname_Patient as 'ФИО пациента', Surname_Employee + ' ' + Name_Employee + ' ' + Midname_Employee as 'ФИО лечащего врача', Name_Disease as 'Заболевание', Name_Severity as 'Тяжесть', Number_Ward as 'Номер палаты' from patientcards join medical_cards on medical_cards.id_card = patientcards.id_card join Employees on Employees.ID_Employee = PatientCards.ID_Employee join Diseases on Diseases.ID_Disease = PatientCards.ID_Disease join Disease_Severity on Disease_Severity.ID_Severity = PatientCards.ID_Severity join Wards on Wards.ID_Ward = PatientCards.ID_Ward"; dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView2.DataSource = dataSet.Tables[0]; debugAndTrace.writeInFile("Включена вкладка \"Карты пациентов\""); break; case 2: costL.Text = "Общая стоимость: 0"; query = $"select id_drugs as 'ID', name_drugs as 'Лекарство', price_drugs as 'Цена' from drugs"; dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView3.DataSource = dataSet.Tables[0]; debugAndTrace.writeInFile("Включена вкладка \"Лекарства\""); break; case 3: if (!passwordFounded) { checkPasswordTB.Text = ""; panel1.Visible = true; } debugAndTrace.writeInFile("Включена вкладка \"Профиль\""); SqlCommand a = new SqlCommand($"select surname_employee from employees where id_employee like '{auth.userID}'", sqlConnection); newSuraname_employeeTB.Text = a.ExecuteScalar().ToString(); a = new SqlCommand($"select name_employee from employees where id_employee like '{auth.userID}'", sqlConnection); newName_employeeTB.Text = a.ExecuteScalar().ToString(); a = new SqlCommand($"select midname_employee from employees where id_employee like N'{auth.userID}'", sqlConnection); newMidname_employeeTB.Text = a.ExecuteScalar().ToString(); a = new SqlCommand($"select name_gender from gender join employees on employees.id_gender = gender.id_gender where id_employee like {auth.userID}", sqlConnection); genderTB.Text = a.ExecuteScalar().ToString(); a = new SqlCommand($"select date_birthday_employee from employees where id_employee like '{auth.userID}'", sqlConnection); DateTime date = DateTime.Parse(a.ExecuteScalar().ToString()); birthdateDTP.Text = $"{date.Day}.{date.Month}.{date.Year}"; a = new SqlCommand($"select telephone_employee from employees where id_employee like '{auth.userID}'", sqlConnection); newTelephone_employeeMTB.Text = a.ExecuteScalar().ToString(); a = new SqlCommand($"select passport_number_employee from employees where id_employee like {auth.userID}", sqlConnection); passportNumberMTB.Text = a.ExecuteScalar().ToString(); a = new SqlCommand($"select passport_place_employee from employees where id_employee like {auth.userID}", sqlConnection); newPassport_place_employeeTB.Text = a.ExecuteScalar().ToString(); a = new SqlCommand($"select passport_code_employee from employees where id_employee like {auth.userID}", sqlConnection); passportCodeMTB.Text = a.ExecuteScalar().ToString(); a = new SqlCommand($"select passport_date_employee from employees where id_employee like {auth.userID}", sqlConnection); passportDateDTP.Text = a.ExecuteScalar().ToString(); break; } } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void button3_Click(object sender, EventArgs e) { try { var res = MessageBox.Show("Вы уверены, что хотите удалить данные?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if(res == DialogResult.Yes) { string row = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString(); SqlCommand a = new SqlCommand($"delete from medical_cards where id_card = {row}", sqlConnection); a.ExecuteNonQuery(); dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView1.DataSource = dataSet.Tables[0]; debugAndTrace.writeInFile($"Удалена медицинская карта {row}"); } else { MessageBox.Show("Действие отменено", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void button2_Click(object sender, EventArgs e) { try { index = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString(); updateMedCard update = new updateMedCard(); update.Show(); debugAndTrace.writeInFile($"Переход на форму изменения медицинской карты {index}"); update.FormClosing += (obj, args) => { dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView1.DataSource = dataSet.Tables[0]; }; } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void button1_Click(object sender, EventArgs e) { try { insertMedCard insert = new insertMedCard(); insert.Show(); debugAndTrace.writeInFile("Переход на форму добавления медицинской карты"); insert.FormClosing += (obj, args) => { dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView1.DataSource = dataSet.Tables[0]; }; } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void add_patientCard_Click(object sender, EventArgs e) { try { insertPatientCard insert = new insertPatientCard(); insert.Show(); debugAndTrace.writeInFile($"Переход на форму записи пациента в палату"); insert.FormClosing += (obj, args) => { dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView2.DataSource = dataSet.Tables[0]; }; } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void delete_patientCard_Click(object sender, EventArgs e) { try { string row = dataGridView2.Rows[dataGridView2.CurrentCell.RowIndex].Cells[0].Value.ToString(); SqlCommand a = new SqlCommand($"update wards set isfree = 1 where id_ward like (select id_ward from patientcards where id_patientcard like {row})", sqlConnection); a.ExecuteNonQuery(); a = new SqlCommand($"update medical_cards set isill = 0 where id_card like (select id_card from patientcards where id_patientcard like {row})", sqlConnection); a.ExecuteNonQuery(); a = new SqlCommand($"delete from patientcards where id_patientcard like {row}", sqlConnection); a.ExecuteNonQuery(); dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView2.DataSource = dataSet.Tables[0]; a = new SqlCommand($"select id_card from patientcards where id_patientcard like {row}", sqlConnection); debugAndTrace.writeInFile($"Пациент {row} выписан из палаты {a.ExecuteScalar()}"); } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } bool passwordFounded = false; private void button1_Click_1(object sender, EventArgs e) { try { SqlCommand a = new SqlCommand($"select password from employees where id_employee like '{auth.userID}'", sqlConnection); Array.Resize(ref auth.data, 1); auth.data[0] = "Пароль: " + checkPasswordTB.Text.GetHashCode(); if (checkPasswordTB.Text.GetHashCode().ToString().Equals(a.ExecuteScalar())) { panel1.Visible = false; passwordFounded = true; debugAndTrace.writeInFile($"Удачный вход на панель редактирования пользователя {auth.userID}", auth.data); } else { MessageBox.Show("Пароли не совпадают!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile($"Неудачный вход на панель редактирования пользователя {auth.userID}", auth.data); } } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void button2_Click_1(object sender, EventArgs e)//изменение данных пользователя { try { SqlCommand a = null; if (!String.IsNullOrEmpty(newLoginTB.Text)) { a = new SqlCommand($"select count(*) from employees where login like N'{newLoginTB.Text.GetHashCode()}'", sqlConnection); MessageBox.Show(a.ExecuteScalar().ToString()); if (a.ExecuteScalar().ToString().Equals("0")) { Array.Resize(ref auth.data, auth.data.Length + 1); auth.data[auth.data.Length - 1] = "Логин: " + newLoginTB.Text.GetHashCode().ToString(); a = new SqlCommand($"update employees set login = @login where id_employee like '{auth.userID}'", sqlConnection); a.Parameters.AddWithValue("login", newLoginTB.Text.GetHashCode()); a.ExecuteNonQuery(); } } if (!String.IsNullOrEmpty(newPasswordTB.Text)) { Array.Resize(ref auth.data, auth.data.Length + 1); auth.data[auth.data.Length - 1] = "Пароль: " + newPasswordTB.Text.GetHashCode().ToString(); a = new SqlCommand($"update employees set password = @password where id_employee like {auth.userID}", sqlConnection); a.Parameters.AddWithValue("password", newPasswordTB.Text.GetHashCode()); a.ExecuteNonQuery(); } DateTime date1 = DateTime.Parse(birthdateDTP.Text); DateTime date2 = DateTime.Parse(passportDateDTP.Text); a = new SqlCommand($"update employees set surname_employee = @surname_employee, name_employee = @name_employee, midname_employee = @midname_employee, date_birthday_employee = @date_birthday_employee, telephone_employee = @telephone_employee, passport_number_employee = @passport_number_employee, passport_date_employee = @passport_date_employee, passport_place_employee = @passport_place_employee, passport_code_employee = @passport_code_employee where id_employee like '{auth.userID}'", sqlConnection); a.Parameters.AddWithValue("surname_employee", newSuraname_employeeTB.Text); a.Parameters.AddWithValue("name_employee", newName_employeeTB.Text); a.Parameters.AddWithValue("midname_employee", newMidname_employeeTB.Text); a.Parameters.AddWithValue("date_birthday_employee", $"{date1.Day}/{date1.Month}/{date1.Year}"); a.Parameters.AddWithValue("telephone_employee", newTelephone_employeeMTB.Text); a.Parameters.AddWithValue("passport_number_employee", passportNumberMTB.Text); a.Parameters.AddWithValue("passport_date_employee", $"{date2.Day}/{date2.Month}/{date2.Year}"); a.Parameters.AddWithValue("passport_place_employee", newPassport_place_employeeTB.Text); a.Parameters.AddWithValue("passport_code_employee", passportCodeMTB.Text); Array.Resize(ref auth.data, 9); auth.data[0] = $"Фамилия: " + newSuraname_employeeTB.Text; auth.data[1] = $"Имя: " + newName_employeeTB.Text; auth.data[2] = $"Отчетсво: " + newMidname_employeeTB.Text; auth.data[3] = $"Дата рождения: " + $"{date1.Month}/{date1.Day}/{date1.Year}"; auth.data[4] = $"Телефон: " + newTelephone_employeeMTB.Text; auth.data[5] = $"Серия и номер паспорта: " + passportNumberMTB.Text; auth.data[6] = $"Дата выдачи паспорта: " + $"{date2.Month}/{date2.Day}/{date2.Year}"; auth.data[7] = $"Кем выдан: " + newPassport_place_employeeTB.Text; auth.data[8] = $"Код подразделения: " + passportCodeMTB.Text; if(a.ExecuteNonQuery() == 1) { MessageBox.Show($"Данные успешно изменены", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Information); debugAndTrace.writeInFile($"Редактирование данных пользователя {auth.userID}", auth.data); } else { MessageBox.Show("Произошла ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("Ошибка добавления данных", auth.data); } } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } string[][] recipe = new string[0][]; private void updateRecipe() { try { dataGridView4.Columns.Clear(); dataGridView4.Columns.Add("first", "Название"); dataGridView4.Columns.Add("second", "Количество"); dataGridView4.Columns.Add("third", "Сумма"); dataGridView4.Rows.Clear(); for (int l = 0; l < recipe.Length; l++) { dataGridView4.Rows.Add(); for (int i = 0; i < recipe[l].Length; i++) { dataGridView4.Rows[l].Cells[i].Value = recipe[l][i]; } } } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } int sum = 0; private void addDrugBTN_Click(object sender, EventArgs e) { try { Array.Resize(ref auth.data, 4); Array.Resize(ref recipe, recipe.Length + 1); recipe[recipe.Length - 1] = new string[3]; string drugRow = dataGridView3.Rows[dataGridView3.CurrentCell.RowIndex].Cells[0].Value.ToString(); SqlCommand a = new SqlCommand($"select name_drugs, price_drugs from drugs where id_drugs like '{drugRow}'", sqlConnection); SqlDataReader reader = a.ExecuteReader(); reader.Read(); recipe[recipe.Length - 1][0] = reader.GetString(0); recipe[recipe.Length - 1][1] = amountDrug.Value.ToString(); recipe[recipe.Length - 1][2] = (reader.GetInt32(1) * (int)amountDrug.Value).ToString(); sum += reader.GetInt32(1) * (int)amountDrug.Value; auth.data[0] = $"Название добавленного лекарства: {reader.GetString(0)}"; auth.data[1] = $"Количество добавленного лекарства: {amountDrug.Value}"; auth.data[2] = $"Цена добавленного лекарства: {(reader.GetInt32(1) * (int)amountDrug.Value).ToString()}"; auth.data[3] = $"Общая стоимость: {sum}"; reader.Close(); updateRecipe(); costL.Text = $"Общая стоимость: {sum}"; debugAndTrace.writeInFile($"Добавление лекарства {drugRow} в рецепт", auth.data); } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void clearBTN_Click(object sender, EventArgs e) { try { Array.Resize(ref recipe, 0); updateRecipe(); debugAndTrace.writeInFile("Очистка рецепта"); } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void button3_Click_1(object sender, EventArgs e) { try { insertDrug insert = new insertDrug(); insert.Show(); debugAndTrace.writeInFile("Переход на форму добавления лекарства"); insert.FormClosing += (obj, args) => { dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView3.DataSource = dataSet.Tables[0]; }; } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void button3_Click_2(object sender, EventArgs e) { try { index = dataGridView3.Rows[dataGridView3.CurrentCell.RowIndex].Cells[0].Value.ToString(); updateDrug update = new updateDrug(); update.Show(); debugAndTrace.writeInFile("Переход на форму изменения лекарства"); update.FormClosing += (obj, args) => { dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView3.DataSource = dataSet.Tables[0]; }; } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void deleteDrugsBTN_Click(object sender, EventArgs e) { try { var res = MessageBox.Show("Вы уверены, что хотите удалить данные?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (res == DialogResult.Yes) { string row = dataGridView3.Rows[dataGridView3.CurrentCell.RowIndex].Cells[0].Value.ToString(); SqlCommand a = new SqlCommand($"delete from drugs where id_drugs = {row}", sqlConnection); a.ExecuteNonQuery(); dataAdapter = new SqlDataAdapter(query, sqlConnection); dataSet = new DataSet(); dataAdapter.Fill(dataSet); dataGridView3.DataSource = dataSet.Tables[0]; debugAndTrace.writeInFile($"Удалено лекарство {row}"); } else { MessageBox.Show("Действие отменено", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch { MessageBox.Show("Произошла непредваиденная ошибка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); debugAndTrace.writeInFile("ERROR"); } } private void label9_Click(object sender, EventArgs e) { } string header = "Рецепт", text = ""; private void print_Click(object sender, EventArgs e) { for (int i = 0; i < recipe.Length; i++) { for (int j = 0; j < recipe[i].Length; j++) { if(j == recipe[i].Length - 1) { text += $"{recipe[i][j]}."; } else { text += $"{recipe[i][j]},"; } } text += "\n"; } PrintDocument doc = new PrintDocument(); doc.PrintPage += PrintPageHandler; PrintDialog dial = new PrintDialog(); dial.Document = doc; if (dial.ShowDialog() == DialogResult.OK) { dial.Document.Print(); } } void PrintPageHandler(object sender, PrintPageEventArgs e) { e.Graphics.DrawString(header, new Font("Times New Roman", 18), Brushes.Black, 240, 30); e.Graphics.DrawString(text, new Font("Times New Roman", 14), Brushes.Black, 10, 100); } } }