카테고리 없음

조회 기능 Lookup 함수 - 2가지 버전

joo_coding 2025. 11. 7. 15:50

1. static 변수 사용

        private void btn_lookup_Click(object sender, EventArgs e)
        {
            DataGridView grid = new DataGridView();
            
            int rowIndex = MainGrid.CurrentCell.RowIndex; 

            string name = MainGrid.Rows[rowIndex].Cells[0].Value.ToString(); // 이름
            int age = Convert.ToInt32(MainGrid.Rows[rowIndex].Cells[1].Value); // 나이
            string major = MainGrid.Rows[rowIndex].Cells[2].Value.ToString(); // 전공

            CurrentName = name;
            CurrentAge = age;
            CurrentMajor = major;

            DetailForm detailForm = new DetailForm();

            detailForm.ShowDialog();

        }

 

        public DetailForm()
        {
            InitializeComponent();

            textBoxName.Text = MainForm.CurrentName ;
            textBoxAge.Text = MainForm.CurrentAge.ToString();
            textBoxMajor.Text = MainForm.CurrentMajor;

        }

 

>> 간단하지만, 전역 상태를 만들어서 나중에 유지보수가 어려워짐. (특히 여러 폼이 동시에 열릴 경우 충돌 위험)

 

✅ 장점

구현 간단 딱 몇 줄로 데이터 공유 가능 (MainForm.CurrentName 바로 접근)
어디서든 접근 가능 다른 클래스나 폼에서도 쉽게 참조할 수 있음

❌ 단점

전역 상태(Global State) 프로그램 전체에서 공유되므로, 여러 폼/스레드가 동시에 접근하면 값이 섞이거나 꼬일 수 있음
의존성 높음 DetailForm이 MainForm의 내부(static 변수)에 직접 의존 → 유지보수 어렵고 재사용 불가
디버깅 어려움 값이 어디서 바뀌는지 추적하기 어려움
동시 실행 불가 DetailForm 여러 개를 동시에 띄우면 전부 같은 데이터 공유됨 😵

💬 예시 문제

  • DetailForm을 두 개 열면 둘 다 같은 static 변수값을 읽어버림 → 내용이 겹침
  • 나중에 다른 폼(예: “학생 수정” 폼)에서도 static 변수 써버리면 데이터 꼬임

2. 메서드 호출

        private void btn_lookup_Click(object sender, EventArgs e)
        {
            int rowIndex = MainGrid.CurrentCell.RowIndex; 

            string name = MainGrid.Rows[rowIndex].Cells[0].Value.ToString(); // 이름
            int age = Convert.ToInt32(MainGrid.Rows[rowIndex].Cells[1].Value); // 나이
            string major = MainGrid.Rows[rowIndex].Cells[2].Value.ToString(); // 전공

            DetailForm detailForm = new DetailForm();

            detailForm.tossName = name;
            detailForm.tossAge = age;
            detailForm.tossMajor = major;

            detailForm.refreshUi();
            detailForm.ShowDialog();

        }
        public string tossName { get; set; }
        public int tossAge { get; set; }
        public string tossMajor { get; set; }

        public void refreshUi()
        {
            labelName.Text = tossName;
            labelAge.Text = tossAge.ToString();
            labelMajor.Text = tossMajor;
        }

 

>> DetailFrom 객체를 먼저 생성한 후, 메인에서 저장한 값을 넘겨주고, refreshUi 함수 실행 후 팝업

 

✅ 장점

객체 간 독립성 보장 폼마다 데이터가 분리되어, 여러 창을 띄워도 안전
유지보수 용이 MainForm, DetailForm이 서로 독립 → 수정 시 영향 최소화
테스트 용이 객체 단위로 테스트 가능 (DetailForm.refreshUi()만 따로 테스트 가능)
확장성 높음 이후 생성자 기반 전달, 인터페이스 주입 등으로 발전시키기 쉬움

❌ 단점

코드 몇 줄 더 필요 tossName = name; 등 명시적으로 세팅해야 함
생성자/속성 세팅 순서 주의 필요 refreshUi()를 너무 일찍 호출하면 값이 안 들어간 상태일 수 있음