Form1.
cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace diplomwork
{
public partial class Form1 : Form
{
private string connectionString = "Data Source=(LocalDB)\\
MSSQLLocalDB;AttachDbFilename=C:\\Users\\egorb\\Desktop\\С#\\diplomwork\\diplomwork\\
Users.mdf;Integrated Security=True";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
private void LoginButton_Click(object sender, EventArgs e)
{
if (registerCheckBox.Checked)
{
// Perform registration
RegisterUser(usernameTextBox.Text, passwordTextBox.Text);
}
else
{
// Perform login
bool isAuthenticated = AuthenticateUser(usernameTextBox.Text,
passwordTextBox.Text);
if (isAuthenticated)
{
MessageBox.Show("Вхід успішний!");
Form2 form2 = new Form2();
form2.Show();
this.Hide();
}
}
private void RegisterCheckBox_CheckedChanged(object sender, EventArgs e)
{
}
private bool AuthenticateUser(string username, string password)
{
try
{
bool isAuthenticated = false;
// Підключення до бази даних
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Перевірити, чи існує користувач з таким логіном
string query = "SELECT COUNT(*) FROM Users WHERE Username = @Username";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Username", username);
int userCount = (int)command.ExecuteScalar();
if (userCount == 0)
{
MessageBox.Show("Користувача з таким логіном не знайдено.");
}
else
{
// Перевірити пароль
query = "SELECT COUNT(*) FROM Users WHERE Username = @Username AND
Password = @Password";
command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Username", username);
command.Parameters.AddWithValue("@Password", password);
int count = (int)command.ExecuteScalar();
isAuthenticated = count > 0;
if (!isAuthenticated)
{
MessageBox.Show("Неправильний пароль.");
}
}
}
return isAuthenticated;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
private void RegisterUser(string username, string password)
{
try
{
// Підключення до бази даних
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Запит для вставки нового користувача
string query = "INSERT INTO Users (Username, Password) VALUES (@Username,
@Password)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Username", username);
command.Parameters.AddWithValue("@Password", password);
// Виконання запиту
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Реєстрація успішна!");
}
else
{
MessageBox.Show("Помилка реєстрації.");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Form2.cs
using diplomwork;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace diplomwork
{
public partial class Form2 : Form
{
private string connectionString = "Data Source=(LocalDB)\\
MSSQLLocalDB;AttachDbFilename=C:\\Users\\egorb\\Desktop\\С#\\diplomwork\\
diplomwork\\Patient.mdf;Integrated Security=True";
public Form2()
{
InitializeComponent();
LoadPatientsList();
}
private void LoadPatientsList()
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM Patients";
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
DataGridView.DataSource = dataTable;
// Відстеження кількості рядків у DataGridView
Console.WriteLine($"DataGridView has {DataGridView.Rows.Count}
rows");
DataGridView.Columns["PatientId"].HeaderText = "ID";
DataGridView.Columns["FirstName"].HeaderText = "Ім'я";
DataGridView.Columns["LastName"].HeaderText = "Фамілія";
DataGridView.Columns["DateOfBirth"].HeaderText = "Дата
народження";
DataGridView.Columns["PhoneNumber"].HeaderText = "Номер
телефону";
DataGridView.Columns["Email"].HeaderText = "Email";
DataGridView.Columns["Address"].HeaderText = "Адреса";
DataGridView.Columns["City"].HeaderText = "Місто";
DataGridView.Columns["State"].HeaderText = "Область";
DataGridView.Columns["ZipCode"].HeaderText = "Zip Code";
DataGridView.Columns["Country"].HeaderText = "Країна";
DataGridView.Columns["CreatedAt"].HeaderText = "Створено";
DataGridView.Columns["UpdatedAt"].HeaderText = "Оновлено";
DataGridView.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show("Error loading patients: " + ex.Message);
}
private void button1_Click(object sender, EventArgs e)
{
AddPatientForm addEditForm = new AddPatientForm();
addEditForm.StartPosition = FormStartPosition.CenterParent; //
Встановлюємо центроване становище щодо батьківської форми
addEditForm.ShowDialog(this); // Відкриваємо форму модально щодо
поточної форми
if (addEditForm.DialogResult == DialogResult.OK)
{
LoadPatientsList(); // Оновлюємо список пацієнтів після додавання
нового
}
int nextPatientId = DataGridView.Rows.Count + 1;
private void button2_Click(object sender, EventArgs e)
{
if(DataGridView.SelectedRows.Count > 0)
{
int selectedPatientId =
(int)DataGridView.SelectedRows[0].Cells["PatientId"].Value;
EditPatientForm editForm = new EditPatientForm(selectedPatientId);
if (editForm.ShowDialog() == DialogResult.OK)
{
LoadPatientsList();
}
}
else
{
MessageBox.Show("Please select a patient to edit.");
}
}
private void button3_Click(object sender, EventArgs e)
{
if (DataGridView.SelectedRows.Count > 0)
{
int selectedPatientId =
(int)DataGridView.SelectedRows[0].Cells["PatientId"].Value;
DeletePatient(selectedPatientId);
}
else
{
MessageBox.Show("Please select a patient to delete.");
}
}
private void DeletePatient(int patientId)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
try
{
// Видалення обраного пацієнта
string deleteQuery = "DELETE FROM Patients WHERE PatientId =
@PatientId";
SqlCommand deleteCommand = new SqlCommand(deleteQuery,
connection, transaction);
deleteCommand.Parameters.AddWithValue("@PatientId", patientId);
deleteCommand.ExecuteNonQuery();
// Створення тимчасової таблиці та вставка даних з оригінальної
таблиці
string createTempTableQuery = "CREATE TABLE #TempPatients
(FirstName NVARCHAR(50), LastName NVARCHAR(50), DateOfBirth DATE,
PhoneNumber NVARCHAR(20), Email NVARCHAR(50), Address NVARCHAR(100), City
NVARCHAR(50), State NVARCHAR(50), ZipCode NVARCHAR(10), Country
NVARCHAR(50), CreatedAt DATETIME, UpdatedAt DATETIME)";
SqlCommand createTempTableCommand = new
SqlCommand(createTempTableQuery, connection, transaction);
createTempTableCommand.ExecuteNonQuery();
string insertDataQuery = "INSERT INTO #TempPatients (FirstName,
LastName, DateOfBirth, PhoneNumber, Email, Address, City, State, ZipCode,
Country, CreatedAt, UpdatedAt) " +
"SELECT FirstName, LastName, DateOfBirth,
PhoneNumber, Email, Address, City, State, ZipCode, Country, CreatedAt, UpdatedAt
"+
"FROM Patients " +
"WHERE PatientId <> @PatientId";
SqlCommand insertDataCommand = new
SqlCommand(insertDataQuery, connection, transaction);
insertDataCommand.Parameters.AddWithValue("@PatientId",
patientId);
insertDataCommand.ExecuteNonQuery();
// Очищення оригінальної таблиці Patients
string truncateTableQuery = "TRUNCATE TABLE Patients";
SqlCommand truncateTableCommand = new
SqlCommand(truncateTableQuery, connection, transaction);
truncateTableCommand.ExecuteNonQuery();
// Вставка даних з тимчасової таблиці в оригінальну таблицю
Patients
string insertBackQuery = "INSERT INTO Patients (FirstName,
LastName, DateOfBirth, PhoneNumber, Email, Address, City, State, ZipCode,
Country, CreatedAt, UpdatedAt) " +
"SELECT FirstName, LastName, DateOfBirth,
PhoneNumber, Email, Address, City, State, ZipCode, Country, CreatedAt, UpdatedAt
"+
"FROM #TempPatients";
SqlCommand insertBackCommand = new
SqlCommand(insertBackQuery, connection, transaction);
insertBackCommand.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
try
{
transaction.Rollback();
}
catch (Exception) { }
MessageBox.Show("Помилка видалення пацієнта: " + ex.Message);
}
finally
{
// Видалення тимчасової таблиці
string dropTempTableQuery = "DROP TABLE #TempPatients";
SqlCommand dropTempTableCommand = new
SqlCommand(dropTempTableQuery, connection);
dropTempTableCommand.ExecuteNonQuery();
}
}
LoadPatientsList();
}
catch (Exception ex)
{
MessageBox.Show("Помилка видалення пацієнта: " + ex.Message);
}
}
private void AddNewPatient(string firstName, string lastName, DateTime
dateOfBirth, string phoneNumber, string email, string address, string city, string
state, string zipCode, string country)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Patients (FirstName, LastName,
DateOfBirth, PhoneNumber, Email, Address, City, State, ZipCode, Country,
CreatedAt, UpdatedAt) " +
"VALUES (@FirstName, @LastName, @DateOfBirth,
@PhoneNumber, @Email, @Address, @City, @State, @ZipCode, @Country,
@CreatedAt, @UpdatedAt); " +
"SELECT SCOPE_IDENTITY();";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@FirstName", firstName);
command.Parameters.AddWithValue("@LastName", lastName);
command.Parameters.AddWithValue("@DateOfBirth", dateOfBirth);
command.Parameters.AddWithValue("@PhoneNumber",
phoneNumber);
command.Parameters.AddWithValue("@Email", email);
command.Parameters.AddWithValue("@Address", address);
command.Parameters.AddWithValue("@City", city);
command.Parameters.AddWithValue("@State", state);
command.Parameters.AddWithValue("@ZipCode", zipCode);
command.Parameters.AddWithValue("@Country", country);
command.Parameters.AddWithValue("@CreatedAt", DateTime.Now);
command.Parameters.AddWithValue("@UpdatedAt", DateTime.Now);
// Отримання присвоєного значення PatientId
int newPatientId = Convert.ToInt32(command.ExecuteScalar());
Console.WriteLine($"New patient added with PatientId =
{newPatientId}");
}
LoadPatientsList();
}
catch (Exception ex)
{
MessageBox.Show("Error adding new patient: " + ex.Message);
}
}
}
}
AddPatientForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace diplomwork
{
public partial class AddPatientForm : Form
{
public AddPatientForm()
{
InitializeComponent();
}
private string connectionString = "Data Source=(LocalDB)\\
MSSQLLocalDB;AttachDbFilename=C:\\Users\\egorb\\Desktop\\С#\\diplomwork\\diplomwork\\
Patient.mdf;Integrated Security=True";
private void AddEditPatientForm_Load(object sender, EventArgs e)
{
private void btnSave_Click(object sender, EventArgs e)
{
// Отримання даних з елементів керування
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
DateTime dateOfBirth = dtpDateOfBirth.Value;
string phoneNumber = txtPhoneNumber.Text;
string email = txtEmail.Text;
string address = txtAddress.Text;
string city = txtCity.Text;
string state = txtState.Text;
string zipCode = txtZipCode.Text;
string country = txtCountry.Text;
DateTime createdAt = DateTime.Now;
DateTime updatedAt = DateTime.Now;
// Збереження даних у базі даних
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Patients (FirstName, LastName, DateOfBirth,
PhoneNumber, Email, Address, City, State, ZipCode, Country, CreatedAt, UpdatedAt) " +
"VALUES (@FirstName, @LastName, @DateOfBirth, @PhoneNumber, @Email,
@Address, @City, @State, @ZipCode, @Country, @CreatedAt, @UpdatedAt)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@FirstName", firstName);
command.Parameters.AddWithValue("@LastName", lastName);
command.Parameters.AddWithValue("@DateOfBirth", dateOfBirth);
command.Parameters.AddWithValue("@PhoneNumber", phoneNumber);
command.Parameters.AddWithValue("@Email", email);
command.Parameters.AddWithValue("@Address", address);
command.Parameters.AddWithValue("@City", city);
command.Parameters.AddWithValue("@State", state);
command.Parameters.AddWithValue("@ZipCode", zipCode);
command.Parameters.AddWithValue("@Country", country);
command.Parameters.AddWithValue("@CreatedAt", createdAt);
command.Parameters.AddWithValue("@UpdatedAt", updatedAt);
command.ExecuteNonQuery();
}
// Закриття форми
this.DialogResult = DialogResult.OK;
this.Close();
}
}
}
EditPatientForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace diplomwork
{
public partial class EditPatientForm : Form
{
private string connectionString = "Data Source=(LocalDB)\\
MSSQLLocalDB;AttachDbFilename=C:\\Users\\egorb\\Desktop\\С#\\diplomwork\\diplomwork\\
Patient.mdf;Integrated Security=True";
public EditPatientForm()
{
InitializeComponent();
}
private readonly int _patientId;
public EditPatientForm(int patientId)
{
InitializeComponent();
_patientId = patientId;
LoadPatientData();
}
private void LoadPatientData()
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM Patients WHERE PatientId = @PatientId";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@PatientId", _patientId);
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
txtFirstName.Text = reader["FirstName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
dtpDateOfBirth.Value = Convert.ToDateTime(reader["DateOfBirth"]);
txtPhoneNumber.Text = reader["PhoneNumber"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtCity.Text = reader["City"].ToString();
txtState.Text = reader["State"].ToString();
txtZipCode.Text = reader["ZipCode"].ToString();
txtCountry.Text = reader["Country"].ToString();
}
reader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error loading patient data: " + ex.Message);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
DateTime dateOfBirth = dtpDateOfBirth.Value;
string phoneNumber = txtPhoneNumber.Text;
string email = txtEmail.Text;
string address = txtAddress.Text;
string city = txtCity.Text;
string state = txtState.Text;
string zipCode = txtZipCode.Text;
string country = txtCountry.Text;
DateTime updatedAt = DateTime.Now;
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "UPDATE Patients SET FirstName = @FirstName, LastName =
@LastName, DateOfBirth = @DateOfBirth, PhoneNumber = @PhoneNumber, Email = @Email,
Address = @Address, City = @City, State = @State, ZipCode = @ZipCode, Country = @Country,
UpdatedAt = @UpdatedAt WHERE PatientId = @PatientId";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@FirstName", firstName);
command.Parameters.AddWithValue("@LastName", lastName);
command.Parameters.AddWithValue("@DateOfBirth", dateOfBirth);
command.Parameters.AddWithValue("@PhoneNumber", phoneNumber);
command.Parameters.AddWithValue("@Email", email);
command.Parameters.AddWithValue("@Address", address);
command.Parameters.AddWithValue("@City", city);
command.Parameters.AddWithValue("@State", state);
command.Parameters.AddWithValue("@ZipCode", zipCode);
command.Parameters.AddWithValue("@Country", country);
command.Parameters.AddWithValue("@UpdatedAt", updatedAt);
command.Parameters.AddWithValue("@PatientId", _patientId);
command.ExecuteNonQuery();
}
this.DialogResult = DialogResult.OK;
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error updating patient: " + ex.Message);
}
}
}
}
CancerExamineForm
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;
namespace diplomwork
{
public partial class CancerExamine : Form
{
private string connectionString = "Data Source=(LocalDB)\\
MSSQLLocalDB;AttachDbFilename=C:\\Users\\egorb\\Desktop\\С#\\diplomwork\\diplomwork\\
Patient.mdf;Integrated Security=True";
private Dictionary<string, string> checkBoxToSymptomMap = new Dictionary<string,
string>();
private Dictionary<HashSet<string>, string> symptomsToTumorType;
public CancerExamine()
{
InitializeComponent();
LoadPatientsList();
checkBoxToSymptomMap.Add("checkBox1", "Незрозуміла втрата ваги");
checkBoxToSymptomMap.Add("checkBox2", "Постійна втома");
checkBoxToSymptomMap.Add("checkBox3", "Кашель або хрипи, що не проходять");
checkBoxToSymptomMap.Add("checkBox4", "Зміна звичок випорожнення або
сечовипускання");
checkBoxToSymptomMap.Add("checkBox5", "Тривала гарячка або нічна пітливість");
checkBoxToSymptomMap.Add("checkBox6", "Біль у грудях");
checkBoxToSymptomMap.Add("checkBox7", "Ненормальні виділення");
checkBoxToSymptomMap.Add("checkBox8", "Рак на шкірі або піднята бородавка");
checkBoxToSymptomMap.Add("checkBox9", "Часте запалення горла");
checkBoxToSymptomMap.Add("checkBox10", "Проблеми з ковтанням");
checkBoxToSymptomMap.Add("checkBox11", "Хрипкий голос");
checkBoxToSymptomMap.Add("checkBox12", "Важке або болісне сечовипускання");
checkBoxToSymptomMap.Add("checkBox13", "Кров у калі або сечі");
checkBoxToSymptomMap.Add("checkBox14", "Нове утворення або горбок на грудях");
checkBoxToSymptomMap.Add("checkBox15", "Часті запори або діарея");
checkBoxToSymptomMap.Add("checkBox16", "Болі в животі");
checkBoxToSymptomMap.Add("checkBox17", "Печія або кислотний рефлюкс");
checkBoxToSymptomMap.Add("checkBox18", "Постійні головні болі");
checkBoxToSymptomMap.Add("checkBox19", "Поява синців або крововиливів");
checkBoxToSymptomMap.Add("checkBox20", "Збільшені лімфатичні вузли");
checkBoxToSymptomMap.Add("checkBox21", "Судоми або параліч");
checkBoxToSymptomMap.Add("checkBox22", "Тривалий дискомфорт у горлі");
checkBoxToSymptomMap.Add("checkBox23", "Гикавка або кашель, що не проходить");
checkBoxToSymptomMap.Add("checkBox24", "Білі плями на язиці або ротовій
порожнині");
checkBoxToSymptomMap.Add("checkBox25", "Свербіж шкіри або почервоніння");
symptomsToTumorType = new Dictionary<HashSet<string>, string>
{
{ new HashSet<string> { "Незрозуміла втрата ваги", "Постійна втома", "Збільшені
лімфатичні вузли", "Тривала гарячка або нічна пітливість" }, "Лімфома" },
{ new HashSet<string> { "Кашель або хрипи, що не проходять", "Біль у грудях",
"Часте запалення горла", "Хрипкий голос", "Кров у калі або сечі" }, "Рак легенів" },
{ new HashSet<string> { "Зміна звичок випорожнення або сечовипускання", "Кров у
калі або сечі", "Часті запори або діарея", "Болі в животі" }, "Рак товстої кишки" },
{ new HashSet<string> { "Проблеми з ковтанням", "Втрата ваги", "Печія або
кислотний рефлюкс", "Болі в животі" }, "Рак шлунка" },
{ new HashSet<string> { "Кров у калі або сечі", "Важке або болісне
сечовипускання" }, "Рак сечового міхура/нирок" },
{ new HashSet<string> { "Тривалий дискомфорт у горлі", "Гикавка або кашель, що
не проходить", "Білі плями на язиці або ротовій порожнині" }, "Рак голови та шиї" },
{ new HashSet<string> { "Рак на шкірі або піднята бородавка", "Свербіж шкіри або
почервоніння" }, "Рак шкіри" },
{ new HashSet<string> { "Постійні головні болі", "Судоми або параліч" }, "Рак
мозку" },
{ new HashSet<string> { "Ненормальні виділення", "Нове утворення або горбок на
грудях" }, "Рак грудей" },
{ new HashSet<string> { "Поява синців або крововиливів" }, "Невідомий тип раку" }
};
private void CancerExamine_Load(object sender, EventArgs e)
{
private void LoadPatientsList()
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT PatientId, FirstName, LastName, DateOfBirth, PhoneNumber,
Email, Address, City, State, ZipCode, Country, CreatedAt, UpdatedAt FROM Patients";
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
// Налаштування заголовків стовпців
dataGridView1.Columns["PatientId"].HeaderText = "ID";
dataGridView1.Columns["FirstName"].HeaderText = "Ім'я";
dataGridView1.Columns["LastName"].HeaderText = "Фамілія";
dataGridView1.Columns["DateOfBirth"].HeaderText = "Дата народження";
dataGridView1.Columns["PhoneNumber"].HeaderText = "Номер телефону";
dataGridView1.Columns["Email"].HeaderText = "Email";
dataGridView1.Columns["Address"].HeaderText = "Адреса";
dataGridView1.Columns["City"].HeaderText = "Місто";
dataGridView1.Columns["State"].HeaderText = "Область";
dataGridView1.Columns["ZipCode"].HeaderText = "Zip Code";
dataGridView1.Columns["Country"].HeaderText = "Країна";
dataGridView1.Columns["CreatedAt"].HeaderText = "Створено";
dataGridView1.Columns["UpdatedAt"].HeaderText = "Оновлено";
// Додавання нових стовпців для типу раку та стадії
dataGridView1.Columns.Add("CancerType", "Тип раку");
dataGridView1.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show("Error loading patients: " + ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
DataGridViewRow selectedRow = dataGridView1.SelectedRows[0];
int patientId = Convert.ToInt32(selectedRow.Cells["PatientId"].Value);
string cancerType = CalculateCancerType();
selectedRow.Cells["CancerType"].Value = cancerType;
}
else
{
MessageBox.Show("Будь ласка, виберіть пацієнта в DataGridView.");
}
}
private string CalculateCancerType()
{
HashSet<string> selectedSymptoms = new HashSet<string>();
foreach (CheckBox checkbox in this.Controls.OfType<CheckBox>())
{
if (checkbox.Checked && checkBoxToSymptomMap.ContainsKey(checkbox.Name))
{
selectedSymptoms.Add(checkBoxToSymptomMap[checkbox.Name]);
}
}
int maxOverlap = 0;
string mostLikelyTumorType = "Невідомий тип раку";
foreach (var symptomsSet in symptomsToTumorType.Keys)
{
int overlap = symptomsSet.Intersect(selectedSymptoms).Count();
if (overlap > maxOverlap)
{
maxOverlap = overlap;
mostLikelyTumorType = symptomsToTumorType[symptomsSet];
}
}
return mostLikelyTumorType;
}
private void checkBox20_CheckedChanged(object sender, EventArgs e)
{
private int DetermineStageFromSymptom(string symptom)
{
// Реалізуйте логіку визначення стадії раку на основі симптому
// Наприклад, можна використати словник для зіставлення симптомів зі стадіями
// або реалізувати більш складну логіку на основі клінічних даних.
// Для прикладу, повернемо значення від 1 до 4 в залежності від перших символів
симптому.
char firstChar = symptom[0];
switch (firstChar)
{
case 'К':
return 4;
case 'Н':
return 3;
case 'П':
return 2;
default:
return 1;
}
}
}
}