kursovaya/AddStudent.axaml.cs
2025-06-09 19:11:36 +03:00

73 lines
2.1 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using kursovaya.Models;
namespace kursovaya;
public partial class AddStudent : Window
{
List<Group> _groups = new List<Group>();
Group group = new Group();
List<Student> students = new List<Student>();
Student student = new Student();
User user = new User();
public AddStudent()
{
InitializeComponent();
using var ctx = new DatabaseContext();
_groups = ctx.Groups.ToList();
GroupsComboBox.ItemsSource = _groups.Select(g => g.Id).ToList();
}
private void ButtonAdd_OnClick(object? sender, RoutedEventArgs e)
{
if (GroupsComboBox.SelectedItem == null ||
string.IsNullOrWhiteSpace(FioTextBox?.Text))
{
ErrorMessage.Text = "Поля не должны быть пустыми!";
return;
}
var fio = FioTextBox.Text;
var selectedGroupId = (int)GroupsComboBox.SelectedItem;
var ctx = new DatabaseContext();
int lastUserId = ctx.Users.Max(u => u.Id);
user = new User() {Id = lastUserId+1, Login = $"user{lastUserId+1}", Password = "qwerty", Email = $"user{lastUserId+1}@mail.ru", RoleId = 1};
student = new Student() {Id = lastUserId+1, Fio = fio, IdGroup = selectedGroupId, Login = $"user{lastUserId+1}"};
ctx.Users.Add(user);
ctx.Students.Add(student);
var changes = ctx.SaveChanges();
if (changes > 0)
{
SuccessMessage.Text = "Ученик успешно добавлен!";
if (ErrorMessage != null)
{
ErrorMessage.Text = "";
}
students.Add(student);
}
else
{
ErrorMessage.Text = "Не удалось добавить ученика.";
SuccessMessage.Text = "";
}
}
private void ButtonBack_OnClick(object? sender, RoutedEventArgs e)
{
Close(students);
}
}