학생 조회 프로그램

2025. 11. 3. 18:56·C#

StudentApp.sln
0.00MB

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StudentApp
{
    internal class Student
    {
        // 속성
        public string Name { get; set; }
        public int Age { get; set; }
        public string Major { get; set; }

        // 생성자
        public Student(string name, int age, string major)
        {
            Name = name;
            Age = age;
            Major = major;
        }

        // 메서드
        public string Introduce()
        {
            return $"안녕하세요, 저는 {Name}이고, 나이는 {Age}살이며, 전공은 {Major}입니다.";
        }
    }
}

Form1.cs

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.IO; // 파일스트림

namespace StudentApp
{
    public partial class Form1 : Form
    {

        private List<Student> students = new List<Student>(); // 학생 리스트

        public Form1()
        {
            InitializeComponent();
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            string name = txtName.Text;

            int age; // TryParse 라는 함수도 있음
            try
            {
                age = int.Parse(txtAge.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("나이는 숫자로 입력해주세요.");
                return;
            }

            string major = txtMajor.Text;

            // 학생 객체 생성
            Student student1 = new Student(name, age, major);

            // 결과 출력
            lbResult.Text = student1.Introduce();

            // 학생 리스트에 추가
            students.Add(student1);
            listStudents.Items.Add(student1.Name);
        }

        // [ini 파일로 저장하는 함수]
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                StreamWriter writer = new StreamWriter("students.ini");

                foreach (var student in students)
                {
                    writer.WriteLine($"[{student.Name}]\nAge={student.Age}\nMajor={student.Major}\n");
                }
                writer.Close();

                MessageBox.Show("저장 완료");
            }

            catch (Exception ex)
            {
                MessageBox.Show("파일 저장 실패");
            }
        }


        // [리스트에서 학생 선택 시 상세 정보 출력] - 마우스로 더블클릭 했을 때
        private void listStudents_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int index = listStudents.SelectedIndex; // 선택한 인덱스번호가 저장돼요

            // SelectedIndex는 선택이 없을 때 -1을 반환하므로 예외처리 필요
            if (index >= 0 && index < students.Count) // 인덱스 범위가 정상이라면
            {
                Student selectedStudent = students[index]; // 참조(포인터 같은 개념) - 쉽게 알아보기 위해서 사용
                MessageBox.Show(selectedStudent.Introduce());
            }
        }

        // ini 형식으로 파싱하는 함수
        // 1. 파일 불러오기
        // 2. 파싱하기
        private void parseIniFile()
        {
            // 구현 예정
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                // 파일 열기
                StreamReader reader = new StreamReader("students.ini");
                students.Clear();
                listStudents.Items.Clear();

                // 파싱값을 담을 변수들
                string line;
                string name = "";
                int age = 0;
                string major = "";

                // ~반복문으로 한 줄씩 읽기~
                while ((line = reader.ReadLine()) != null)
                {
                    line = line.Trim(); // 공백 제거

                    // 대괄호 = 섹션 (파싱 시작)
                    if (line.StartsWith("[") && line.EndsWith("]"))
                    {
                        // 이전 학생이 있으면 추가
                        if (!string.IsNullOrEmpty(name))
                        {
                            students.Add(new Student(name, age, major));
                            listStudents.Items.Add(name);
                        }

                        // 새 학생 이름 초기화
                        name = line.Substring(1, line.Length - 2);
                        age = 0;
                        major = "";

                        // [이름]
                        // 이름에 대괄호 제거하고 저장 > 추출을 시작할 문자 위치, 끝나는 위치 (총 길이 -1은 대괄호)
                        // 이름이 3글자 이상일 수 있으니 길이로계산
                    }

                    // [나이]
                    else if (line.StartsWith("Age=")) // 나이 
                    {
                        age = int.Parse(line.Substring(4)); // 4글자 이후부터 끝까지
                    }

                    // [전공]
                    else if (line.StartsWith("Major=")) // 전공
                    {
                        major = line.Substring(6); // 6글자 이후부터 끝까지
                    }

                    // 추가

                }
                if (!string.IsNullOrEmpty(name)) // 이름이 비어있지 않다면
                {
                    students.Add(new Student(name, age, major)); // 학생 리스트에 학생 추가 (일단 기본값으로 먼저 생성)
                    listStudents.Items.Add(name); // 리스트 박스에 이름 추가
                }

                reader.Close(); // 파일 닫기

                MessageBox.Show("불러오기 완료");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
    }
}

'C#' 카테고리의 다른 글

학생 조회 프로그램 - origin 코드  (0) 2025.11.04
학생 조회 프로그램 - 함수 설명 (기능명세서)  (0) 2025.11.04
예외종류 :: 구체적인 예외로 어떤 오류인지 확인하기  (0) 2025.11.03
Auto-Property  (0) 2025.11.03
C# 클래스 만들기  (0) 2025.11.03
'C#' 카테고리의 다른 글
  • 학생 조회 프로그램 - origin 코드
  • 학생 조회 프로그램 - 함수 설명 (기능명세서)
  • 예외종류 :: 구체적인 예외로 어떤 오류인지 확인하기
  • Auto-Property
joo_coding
joo_coding
2025.02.18~
  • joo_coding
    주코딩일지
    joo_coding
  • 전체
    오늘
    어제
    • 분류 전체보기 (219)
      • 일지 (19)
      • 계획표 (7)
      • 프로젝트 (6)
      • C언어 (35)
        • 연습장 (12)
      • C++ (3)
      • C# (34)
      • Python (28)
        • 연습장 (11)
      • TCP IP (4)
      • DB (2)
      • ubuntu (1)
      • Git (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    c언어 #vscode #gcc #윈도우 #c언어윈도우 #gcc윈도우 #vscode윈도우 #c #c++
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
joo_coding
학생 조회 프로그램
상단으로

티스토리툴바