• 1405/05/19

تمرین جلسه112 :

 
          
          
          
          
          
          
          
          
سلام استاد وقت به خیر  این کد رابا کمک هوش مصنوعی نوشتمusing DataLayer.Context;
using DataLayer.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace Toplearn_School.Classes
{
    public partial class frmAddOrEditClass : Form
    {
        private TopLearn_DB_Context _context = new TopLearn_DB_Context();
        public bool isEditMode = false;
        private int _courseId = 0;

        // Constructor for Add mode
        public frmAddOrEditClass()
        {
            InitializeComponent();
            isEditMode = false;
            this.Text = "افزودن دوره جدید";
            btnSave.Text = "ثبت";
        }

        // Constructor for Edit mode
        public frmAddOrEditClass(int courseId)
        {
            InitializeComponent();
            isEditMode = true;
            _courseId = courseId;
            this.Text = "ویرایش دوره";
            btnSave.Text = "ویرایش";
        }

        private void frmAddOrEditClass_Load(object sender, EventArgs e)
        {
            BindLists();
            BindDgvPersons();

            if (isEditMode)
            {
                LoadCourseData(_courseId);
                LoadStudentsForCourse(_courseId);
            }
        }

        void BindLists()
        {
            cboTeacher.DataSource = _context.People
                .Where(p => p.IsTeacher == true)
                .Select(p => new
                {
                    FullName = p.Name + " " + p.Family,
                    p.PersonId
                })
                .ToList();
            cboTeacher.DisplayMember = "FullName";
            cboTeacher.ValueMember = "PersonId";
        }

        void BindDgvPersons()
        {
            dgvPersons.AutoGenerateColumns = false;
            dgvPersons.Rows.Clear();

            var list = _context.People.ToList();
            foreach (var person in list)
            {
                string fullName = person.Name + " " + person.Family;
                dgvPersons.Rows.Add(person.PersonId, fullName, person.Mobile, person.Email);
            }
        }

        void LoadCourseData(int courseId)
        {
            var course = _context.Courses
                .FirstOrDefault(c => c.CourseId == courseId);

            if (course != null)
            {
                txtTitle.Text = course.Title;
                txtDescription.Text = course.Description;
                txtClassHours.Value = course.Hours;
                txtStudentCount.Text = course.StudentCount.ToString();

                if (course.TeacherId != null)
                {
                    cboTeacher.SelectedValue = course.TeacherId;
                }
            }
        }

        void LoadStudentsForCourse(int courseId)
        {
            dgvStudentInClass.Rows.Clear();

            var students = _context.StudentInCourses
                .Include(s => s.Person)
                .Where(s => s.CourseId == courseId)
                .ToList();

            foreach (var student in students)
            {
                string fullName = student.Person.Name + " " + student.Person.Family;
                dgvStudentInClass.Rows.Add(student.PersonId, fullName);

                // Hide this student from available grid
                foreach (DataGridViewRow row in dgvPersons.Rows)
                {
                    if (row.Cells[0].Value != null &&
                        row.Cells[0].Value.ToString() == student.PersonId.ToString())
                    {
                        row.Visible = false;
                        break;
                    }
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateInputs())
                return;

            try
            {
                if (!isEditMode)
                {
                    // ADD Mode
                    Course course = new Course();
                    course.Title = txtTitle.Text;
                    course.Description = txtDescription.Text;
                    course.Hours = (int)txtClassHours.Value;
                    course.StudentCount = int.Parse(txtStudentCount.Text);
                    course.TeacherId = int.Parse(cboTeacher.SelectedValue.ToString());
                    _context.Courses.Add(course);
                    _context.SaveChanges();

                    // Add students
                    AddStudentsToCourse(course.CourseId);
                }
                else
                {
                    // EDIT Mode
                    var course = _context.Courses
                        .Include(c => c.StudentInCourses)
                        .FirstOrDefault(c => c.CourseId == _courseId);

                    if (course != null)
                    {
                        course.Title = txtTitle.Text;
                        course.Description = txtDescription.Text;
                        course.Hours = (int)txtClassHours.Value;
                        course.StudentCount = int.Parse(txtStudentCount.Text);
                        course.TeacherId = int.Parse(cboTeacher.SelectedValue.ToString());

                        // Remove existing students
                        if (course.StudentInCourses != null && course.StudentInCourses.Any())
                        {
                            _context.StudentInCourses.RemoveRange(course.StudentInCourses);
                        }

                        // Add new students
                        AddStudentsToCourse(course.CourseId);
                    }
                }

                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                FarsiMessageBox.MessageBox.Show("خطا", $"خطا در ذخیره اطلاعات: {ex.Message}",
                    FarsiMessageBox.MessageBox.Buttons.OK,
                    FarsiMessageBox.MessageBox.Icons.Error);
            }
        }

        private void AddStudentsToCourse(int courseId)
        {
            if (dgvStudentInClass.Rows.Count > 0)
            {
                for (int i = 0; i < dgvStudentInClass.Rows.Count; i++)
                {
                    if (dgvStudentInClass.Rows[i].Cells[0].Value != null)
                    {
                        string personId = dgvStudentInClass.Rows[i].Cells[0].Value.ToString();
                        StudentInCourse inCourse = new StudentInCourse()
                        {
                            CourseId = courseId,
                            PersonId = int.Parse(personId),
                            RegisterDate = DateTime.Now,
                        };
                        _context.StudentInCourses.Add(inCourse);
                    }
                }
                _context.SaveChanges();
            }
        }

        #region Validation
        bool ValidateInputs()
        {
            bool isValid = true;

            if (string.IsNullOrEmpty(txtTitle.Text))
            {
                txtTitle.BackColor = Color.Tomato;
                isValid = false;
            }
            else
            {
                txtTitle.BackColor = Color.White;
            }

            if (string.IsNullOrEmpty(txtStudentCount.Text) || !int.TryParse(txtStudentCount.Text, out _))
            {
                txtStudentCount.BackColor = Color.Tomato;
                isValid = false;
            }
            else
            {
                txtStudentCount.BackColor = Color.White;
            }

            if (txtClassHours.Value == 0)
            {
                txtClassHours.BackColor = Color.Tomato;
                isValid = false;
            }
            else
            {
                txtClassHours.BackColor = Color.White;
            }

            if (cboTeacher.SelectedValue == null)
            {
                cboTeacher.BackColor = Color.Tomato;
                isValid = false;
            }
            else
            {
                cboTeacher.BackColor = Color.White;
            }

            if (dgvStudentInClass.Rows.Count == 0)
            {
                FarsiMessageBox.MessageBox.Show("توجه", "حداقل یک دانشجو باید به کلاس اضافه شود",
                    FarsiMessageBox.MessageBox.Buttons.OK,
                    FarsiMessageBox.MessageBox.Icons.Warning);
                isValid = false;
            }

            return isValid;
        }
        #endregion

        private void txtStudentCount_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtStudentCount.Text))
            {
                if (!int.TryParse(txtStudentCount.Text, out _))
                {
                    txtStudentCount.Text = "";
                }
            }
        }

        private void btnAddToClass_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvPersons.CurrentRow == null)
                {
                    FarsiMessageBox.MessageBox.Show("توجه", "لطفاً ابتدا یک دانشجو را انتخاب کنید",
                        FarsiMessageBox.MessageBox.Buttons.OK,
                        FarsiMessageBox.MessageBox.Icons.Warning);
                    return;
                }

                if (!dgvPersons.CurrentRow.Visible)
                {
                    FarsiMessageBox.MessageBox.Show("توجه", "این دانشجو قبلاً به کلاس اضافه شده است",
                        FarsiMessageBox.MessageBox.Buttons.OK,
                        FarsiMessageBox.MessageBox.Icons.Warning);
                    return;
                }

                string personId = dgvPersons.CurrentRow.Cells[0].Value?.ToString();
                string personName = dgvPersons.CurrentRow.Cells[1].Value?.ToString();

                if (string.IsNullOrEmpty(personId))
                    return;

                // Check if already added
                bool alreadyAdded = false;
                foreach (DataGridViewRow row in dgvStudentInClass.Rows)
                {
                    if (row.Cells[0].Value != null &amp;amp;amp;&amp;amp;amp;
                        row.Cells[0].Value.ToString() == personId)
                    {
                        alreadyAdded = true;
                        break;
                    }
                }

                if (!alreadyAdded)
                {
                    dgvStudentInClass.Rows.Add(personId, personName);
                    dgvPersons.CurrentRow.Visible = false;
                }
                else
                {
                    FarsiMessageBox.MessageBox.Show("توجه", "این دانشجو قبلاً به کلاس اضافه شده است",
                        FarsiMessageBox.MessageBox.Buttons.OK,
                        FarsiMessageBox.MessageBox.Icons.Warning);
                }
            }
            catch (Exception ex)
            {
                FarsiMessageBox.MessageBox.Show("خطا", $"خطا در افزودن دانشجو: {ex.Message}",
                    FarsiMessageBox.MessageBox.Buttons.OK,
                    FarsiMessageBox.MessageBox.Icons.Error);
            }
        }

        // Main Delete Method
        private void btnDeleteStudentInClass_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvStudentInClass.CurrentRow == null)
                {
                    FarsiMessageBox.MessageBox.Show("توجه", "لطفاً ابتدا یک دانشجو را انتخاب کنید",
                        FarsiMessageBox.MessageBox.Buttons.OK,
                        FarsiMessageBox.MessageBox.Icons.Warning);
                    return;
                }

                string personId = dgvStudentInClass.CurrentRow.Cells[0].Value?.ToString();
                string personName = dgvStudentInClass.CurrentRow.Cells[1].Value?.ToString();

                if (string.IsNullOrEmpty(personId))
                    return;

                DialogResult result = FarsiMessageBox.MessageBox.Show(
                    "تأیید حذف",
                    $"آیا از حذف دانشجو '{personName}' از این کلاس مطمئن هستید؟",
                    FarsiMessageBox.MessageBox.Buttons.YesNo,
                    FarsiMessageBox.MessageBox.Icons.Question);

                if (result == DialogResult.Yes)
                {
                    // Remove from database if in edit mode
                    if (isEditMode &amp;amp;amp;&amp;amp;amp; _courseId > 0)
                    {
                        var studentInCourse = _context.StudentInCourses
                            .FirstOrDefault(s => s.CourseId == _courseId &amp;amp;amp;&amp;amp;amp; s.PersonId == int.Parse(personId));

                        if (studentInCourse != null)
                        {
                            _context.StudentInCourses.Remove(studentInCourse);
                            _context.SaveChanges();
                        }
                    }

                    // Remove from grid
                    int rowIndex = dgvStudentInClass.CurrentRow.Index;
                    dgvStudentInClass.Rows.RemoveAt(rowIndex);

                    // Show in available grid
                    foreach (DataGridViewRow row in dgvPersons.Rows)
                    {
                        if (row.Cells[0].Value != null &amp;amp;amp;&amp;amp;amp;
                            row.Cells[0].Value.ToString() == personId)
                        {
                            row.Visible = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FarsiMessageBox.MessageBox.Show("خطا", $"خطا در حذف دانشجو: {ex.Message}",
                    FarsiMessageBox.MessageBox.Buttons.OK,
                    FarsiMessageBox.MessageBox.Icons.Error);
            }
        }

        // Remove button (if you have both buttons)
        private void btnRemoveFromClass_Click(object sender, EventArgs e)
        {
            btnDeleteStudentInClass_Click(sender, e);
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
  • 1405/05/19
  • ساعت 19:36

خیلی هم عالی 

کمک گرفتن هیچ اشکالی نداره