using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows;
namespace Exam_Shafigullin_V19
{
    public partial class MainWindow : Window
    {
        // Строка подключения к базе данных
        private readonly string connectionString = "Data Source=srv-wsr\\is4;user id=user28;password=is4-user28;Initial Catalog=Zarplata;Integrated Security=False";
        public MainWindow()
        {
            InitializeComponent();
            LoadEmployees(); // Загрузка данных при запуске программы
        }
        // Метод для загрузки данных из базы данных в DataGrid
        private void LoadEmployees()
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    
                    string query = @"
                        SELECT 
                            e.EmployeeID AS [Табельный номер],
                            e.FullName AS [ФИО сотрудника],
                            p.PositionName AS [Должность],
                            p.Salary AS [Оклад],
                            e.WorkedHours AS [Отработанные часы]
                        FROM EmployeeCard e
                        INNER JOIN PositionDirectory p ON e.PositionID = p.PositionID";
                    SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
                    DataTable dataTable = new DataTable();
                    adapter.Fill(dataTable);
                    EmployeeGrid.ItemsSource = dataTable.DefaultView;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка загрузки данных: {ex.Message}");
                }
            }
        }
        
        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    
                    string query = @"
                        INSERT INTO EmployeeCard (FullName, PositionID, PayCode, WorkedHours)
                        VALUES (@FullName, @PositionID, @PayCode, @WorkedHours)";
                    SqlCommand command = new SqlCommand(query, connection);
                    command.Parameters.AddWithValue("@FullName", FullNameTextBox.Text);
                    command.Parameters.AddWithValue("@PositionID", int.Parse(PositionIDTextBox.Text));
                    command.Parameters.AddWithValue("@PayCode", int.Parse(PayCodeTextBox.Text));
                    command.Parameters.AddWithValue("@WorkedHours", decimal.Parse(WorkedHoursTextBox.Text));
                    command.ExecuteNonQuery();
                    MessageBox.Show("Сотрудник успешно добавлен!");
                    ClearFields();
                    LoadEmployees();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка при добавлении сотрудника: {ex.Message}");
                }
            }
        }
      
        private void EditButton_Click(object sender, RoutedEventArgs e)
        {
            if (EmployeeGrid.SelectedItem is DataRowView selectedRow)
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    try
                    {
                        connection.Open();
                        
                        string query = @"
                            UPDATE EmployeeCard
                            SET FullName = @FullName,
                                PositionID = @PositionID,
                                PayCode = @PayCode,
                                WorkedHours = @WorkedHours
                            WHERE EmployeeID = @EmployeeID";
                        SqlCommand command = new SqlCommand(query, connection);
                        command.Parameters.AddWithValue("@FullName", FullNameTextBox.Text);
                        command.Parameters.AddWithValue("@PositionID", int.Parse(PositionIDTextBox.Text));
                        command.Parameters.AddWithValue("@PayCode", int.Parse(PayCodeTextBox.Text));
                        command.Parameters.AddWithValue("@WorkedHours", decimal.Parse(WorkedHoursTextBox.Text));
                        command.Parameters.AddWithValue("@EmployeeID", selectedRow["Табельный номер"]);
                        command.ExecuteNonQuery();
                        MessageBox.Show("Данные сотрудника успешно обновлены!");
                        ClearFields();
                        LoadEmployees();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Ошибка при редактировании данных: {ex.Message}");
                    }
                }
            }
            else
            {
                MessageBox.Show("Выберите сотрудника для редактирования.");
            }
        }
     
        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (EmployeeGrid.SelectedItem is DataRowView selectedRow)
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    try
                    {
                        connection.Open();
                        
                        string query = "DELETE FROM EmployeeCard WHERE EmployeeID = @EmployeeID";
                        SqlCommand command = new SqlCommand(query, connection);
                        command.Parameters.AddWithValue("@EmployeeID", selectedRow["Табельный номер"]);
                        command.ExecuteNonQuery();
                        MessageBox.Show("Сотрудник успешно удален!");
                        ClearFields();
                        LoadEmployees();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Ошибка при удалении сотрудника: {ex.Message}");
                    }
                }
            }
            else
            {
                MessageBox.Show("Выберите сотрудника для удаления.");
            }
        }
        // Метод для очистки полей ввода
        private void ClearFields()
        {
            FullNameTextBox.Clear();
            PositionIDTextBox.Clear();
            PayCodeTextBox.Clear();
            WorkedHoursTextBox.Clear();
        }
    }
}
Переделай код снизу под код сверху под тему Нобелевские лауреаты
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly string connectionString = "Data Source=srv-wsr\\is4;user id=user14;password=is4-user14;Initial Catalog=Нобелевские_лауреаты;Integrated Security=False";
        public MainWindow()
        {
            InitializeComponent();
            LoadData();
        }
    }

    private void LoadData()
    {
        List<NobelLaureate> laureates = new List<NobelLaureate>();
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlCommand command = new SqlCommand("SELECT * FROM NobelLaureates", connection);
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                laureates.Add(new NobelLaureate
                {
                    Id = (int)reader["Id"],
                    LastName = reader["LastName"].ToString(),
                    FirstName = reader["FirstName"].ToString(),
                    MiddleName = reader["MiddleName"].ToString(),
                    Country = reader["Country"].ToString(),
                    PrizeField = reader["PrizeField"].ToString(),
                    Year = (int)reader["Year"]
                });
            }
        }
        LaureatesDataGrid.ItemsSource = laureates;
    }

    private void AddButton_Click(object sender, RoutedEventArgs e)
    {
        var addWindow = new AddEditLaureateWindow();
        if (addWindow.ShowDialog() == true)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand("INSERT INTO NobelLaureates (LastName, FirstName, MiddleName, Country, PrizeField, Year) VALUES (@LastName, @FirstName, @MiddleName, @Country, @PrizeField, @Year)", connection);
                command.Parameters.AddWithValue("@LastName", addWindow.LastName);
                command.Parameters.AddWithValue("@FirstName", addWindow.FirstName);
                command.Parameters.AddWithValue("@MiddleName", addWindow.MiddleName);
                command.Parameters.AddWithValue("@Country", addWindow.Country);
                command.Parameters.AddWithValue("@PrizeField", addWindow.PrizeField);
                command.Parameters.AddWithValue("@Year", addWindow.Year);
                command.ExecuteNonQuery();
            }
            LoadData();
        }
    }

    private void EditButton_Click(object sender, RoutedEventArgs e)
    {
        if (LaureatesDataGrid.SelectedItem is NobelLaureate selectedLaureate)
        {
            var editWindow = new AddEditLaureateWindow(selectedLaureate);
            if (editWindow.ShowDialog() == true)
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand("UPDATE NobelLaureates SET LastName=@LastName, FirstName=@FirstName, MiddleName=@MiddleName, Country=@Country, PrizeField=@PrizeField, Year=@Year WHERE Id=@Id", connection);
                    command.Parameters.AddWithValue("@LastName", editWindow.LastName);
                    command.Parameters.AddWithValue("@FirstName", editWindow.FirstName);
                    command.Parameters.AddWithValue("@MiddleName", editWindow.MiddleName);
                    command.Parameters.AddWithValue("@Country", editWindow.Country);
                    command.Parameters.AddWithValue("@PrizeField", editWindow.PrizeField);
                    command.Parameters.AddWithValue("@Year", editWindow.Year);
                    command.Parameters.AddWithValue("@Id", selectedLaureate.Id);
                    command.ExecuteNonQuery();
                }
                LoadData();
            }
        }
        else
        {
            MessageBox.Show("Пожалуйста, выберите лауреата для редактирования.");
        }
    }

    private void DeleteButton_Click(object sender, RoutedEventArgs e)
    {
        if (LaureatesDataGrid.SelectedItem is NobelLaureate selectedLaureate)
        {
            MessageBoxResult result = MessageBox.Show($"Вы уверены, что хотите удалить лауреата {selectedLaureate.LastName}?", "Удаление лауреата", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand("DELETE FROM NobelLaureates WHERE Id=@Id", connection);
                    command.Parameters.AddWithValue("@Id", selectedLaureate.Id);
                    command.ExecuteNonQuery();
                }
                LoadData();
            }
        }
        else
        {
            MessageBox.Show("Пожалуйста, выберите лауреата для удаления.");
        }
    }
}

public class NobelLaureate
{
    public int Id { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string Country { get; set; }
    public string PrizeField { get; set; }
    public int Year { get; set; }
}
}

}