🔎 유용한 정보
1. 강의 개요
이번 강의에서는 DataGridView를 활용하여 데이터를 테이블 형식으로 표시하고, 데이터 바인딩을 통해 데이터 소스와 연결하는 방법을 학습합니다.
또한, 데이터를 추가/수정/삭제하고, 데이터 변경 사항을 UI와 동기화하는 고급 기법을 다룹니다.
2. 학습 목표
- DataGridView의 주요 기능 이해.
- 데이터 바인딩을 사용해 데이터 소스와 DataGridView를 연결.
- 데이터를 동적으로 추가/수정/삭제하는 방법.
3. DataGridView란?
DataGridView는 Windows Forms에서 데이터를 표 형식으로 표시하는 컨트롤입니다.
- 컬렉션(예: List, DataTable) 데이터를 쉽게 연결하여 표시 가능.
- 데이터를 동적으로 추가/삭제/수정 가능.
- 다양한 스타일과 이벤트를 지원.
4. 실습: DataGridView와 데이터 바인딩
요구사항
- List<T>를 데이터 소스로 사용하여 데이터 바인딩 구현.
- DataGridView를 통해 데이터를 표시 및 관리.
- 버튼을 통해 데이터 추가, 수정, 삭제 기능 구현.
폼 구성
컨트롤 타입 이름 텍스트 위치 크기
DataGridView | dataGridView1 | (없음) | 중앙 | (400 x 200) |
Button | btnAdd | "추가" | 하단 왼쪽 | (80 x 30) |
Button | btnUpdate | "수정" | 하단 가운데 | (80 x 30) |
Button | btnDelete | "삭제" | 하단 오른쪽 | (80 x 30) |
코드 작성
1. 클래스 정의
namespace WindowsFormsApp1
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
}
2. Form1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private BindingSource bindingSource; // 데이터 바인딩을 위한 BindingSource
private List<Person> people; // 데이터 저장소
public Form1()
{
InitializeComponent();
InitializeData();
InitializeDataGridView();
InitializeEvents();
}
private void InitializeData()
{
// 초기 데이터 설정
people = new List<Person>
{
new Person { Id = 1, Name = "김철수", Age = 30, Email = "kim@example.com" },
new Person { Id = 2, Name = "이영희", Age = 25, Email = "lee@example.com" },
new Person { Id = 3, Name = "박민수", Age = 35, Email = "park@example.com" }
};
// BindingSource와 데이터 연결
bindingSource = new BindingSource();
bindingSource.DataSource = people;
}
private void InitializeDataGridView()
{
// DataGridView와 BindingSource 연결
dataGridView1.DataSource = bindingSource;
// DataGridView 설정
dataGridView1.AutoGenerateColumns = true; // 컬럼 자동 생성
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 행 선택 모드
dataGridView1.MultiSelect = false; // 다중 선택 불가
}
private void InitializeEvents()
{
btnAdd.Click += BtnAdd_Click;
btnUpdate.Click += BtnUpdate_Click;
btnDelete.Click += BtnDelete_Click;
}
// "추가" 버튼 클릭 이벤트
private void BtnAdd_Click(object sender, EventArgs e)
{
var newPerson = new Person
{
Id = people.Max(p => p.Id) + 1, // 새로운 ID 생성
Name = "새 사용자",
Age = 20,
Email = "newuser@example.com"
};
people.Add(newPerson); // 데이터 추가
bindingSource.ResetBindings(false); // 바인딩 갱신
}
// "수정" 버튼 클릭 이벤트
private void BtnUpdate_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
var selectedPerson = (Person)dataGridView1.CurrentRow.DataBoundItem;
selectedPerson.Name = "수정된 이름";
selectedPerson.Age = 40;
bindingSource.ResetBindings(false); // 바인딩 갱신
}
}
// "삭제" 버튼 클릭 이벤트
private void BtnDelete_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
var selectedPerson = (Person)dataGridView1.CurrentRow.DataBoundItem;
people.Remove(selectedPerson); // 데이터 삭제
bindingSource.ResetBindings(false); // 바인딩 갱신
}
}
}
}
3. Form1.Designer.cs
namespace WindowsFormsApp1
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
private DataGridView dataGridView1;
private Button btnAdd;
private Button btnUpdate;
private Button btnDelete;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.dataGridView1 = new DataGridView();
this.btnAdd = new Button();
this.btnUpdate = new Button();
this.btnDelete = new Button();
this.SuspendLayout();
// dataGridView1
this.dataGridView1.Location = new System.Drawing.Point(20, 20);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(400, 200);
this.dataGridView1.TabIndex = 0;
// btnAdd
this.btnAdd.Location = new System.Drawing.Point(20, 240);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(80, 30);
this.btnAdd.Text = "추가";
this.btnAdd.UseVisualStyleBackColor = true;
// btnUpdate
this.btnUpdate.Location = new System.Drawing.Point(160, 240);
this.btnUpdate.Name = "btnUpdate";
this.btnUpdate.Size = new System.Drawing.Size(80, 30);
this.btnUpdate.Text = "수정";
this.btnUpdate.UseVisualStyleBackColor = true;
// btnDelete
this.btnDelete.Location = new System.Drawing.Point(300, 240);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(80, 30);
this.btnDelete.Text = "삭제";
this.btnDelete.UseVisualStyleBackColor = true;
// Form1
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(450, 300);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnUpdate);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "DataGridView 예제";
this.ResumeLayout(false);
}
}
}
5. 실행 결과
- 초기 상태
- DataGridView에 초기 데이터(이름, 나이, 이메일)가 표시됩니다.
- 데이터 추가
- "추가" 버튼 클릭 → 새로운 행이 추가됩니다.
- 데이터 수정
- DataGridView에서 수정할 행 선택 후 "수정" 버튼 클릭 → 선택된 데이터가 수정됩니다.
- 데이터 삭제
- DataGridView에서 삭제할 행 선택 후 "삭제" 버튼 클릭 → 선택된 데이터가 삭제됩니다.
6. 주요 개념 요약
- DataGridView와 BindingSource
- BindingSource를 통해 컬렉션과 DataGridView를 연결하여 동적 데이터 관리.
- 데이터 동적 추가/수정/삭제
- ResetBindings(false)를 호출하여 UI와 데이터 소스 간의 동기화 유지.
- 행 선택 및 작업
- DataGridView.CurrentRow를 통해 선택된 행의 데이터를 가져와 작업 수행.
'📁 [4] 개발자 정보 & 코드 노트 > C#' 카테고리의 다른 글
C# Windows Forms 강의 51편: 메모장 애플리케이션 제작 (0) | 2025.03.26 |
---|---|
C# Windows Forms 강의 50편: 다중 쓰레드와 ProgressBar 활용 (0) | 2025.03.25 |
C# Windows Forms 강의 48편: 리소스 관리 (이미지, 아이콘, 사운드 파일) (0) | 2025.03.23 |
C# Windows Forms 강의 47편: 폼 간 데이터 전달 방법 (0) | 2025.03.22 |
C# Windows Forms 강의 46편: BackgroundWorker로 비동기 작업 처리 (0) | 2025.03.21 |
🔎 유용한 정보