Study/C#
C# Windows Forms 강의 19편: 데이터 바인딩(Data Binding)과 BindingSource 사용
wawManager
2025. 2. 22. 12:00
728x90
1. 강의 개요
이번 강의에서는 Windows Forms에서 **데이터 바인딩(Data Binding)**을 활용하여 데이터를 컨트롤과 연결하는 방법을 학습합니다.
BindingSource는 데이터 바인딩을 관리하고, 데이터 소스와 UI 컨트롤 간의 상호작용을 간소화합니다.
2. 학습 목표
- DataGridView와 데이터 소스를 연결하여 데이터를 표시 및 편집.
- BindingSource를 사용해 데이터 바인딩을 효율적으로 관리.
- 데이터를 실시간으로 추가, 수정, 삭제하는 방법 학습.
3. 데이터 바인딩이란?
**데이터 바인딩(Data Binding)**은 데이터 소스(예: 컬렉션, 데이터베이스 등)와 UI 컨트롤 간의 연결을 의미합니다.
- 데이터 소스와 UI 간의 데이터를 자동으로 동기화.
- 데이터 변경 시 UI가 자동 업데이트되며, 반대도 가능.
BindingSource란?
BindingSource는 데이터 바인딩을 효율적으로 관리하기 위한 중간 계층 역할을 합니다.
- 데이터 소스와 컨트롤 간의 데이터 흐름을 관리.
- 데이터를 추가, 삭제, 수정할 수 있는 메서드 제공.
4. 실습: 데이터 바인딩과 BindingSource
요구사항
- BindingSource를 사용해 DataGridView와 데이터를 바인딩.
- 텍스트박스를 통해 데이터를 추가 및 수정.
- "추가", "삭제", "저장" 버튼으로 데이터 관리.
폼 구성
컨트롤 타입 이름 텍스트 위치 크기
DataGridView | dataGridView1 | (없음) | 상단 | (400 x 200) |
Label | lblName | "이름:" | 중간 왼쪽 | (50 x 20) |
TextBox | txtName | (없음) | 중간 오른쪽 | (150 x 20) |
Button | btnAdd | "추가" | 하단 왼쪽 | (100 x 30) |
Button | btnDelete | "삭제" | 하단 중간 | (100 x 30) |
Button | btnSave | "저장" | 하단 오른쪽 | (100 x 30) |
코드 작성
1. 데이터 클래스 정의
public class Person
{
public string Name { get; set; }
}
2. Form1.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private BindingSource bindingSource = new BindingSource();
private List<Person> people = new List<Person>();
public Form1()
{
InitializeComponent();
InitializeDataBinding();
}
private void InitializeDataBinding()
{
// 데이터 소스 설정
people.Add(new Person { Name = "홍길동" });
people.Add(new Person { Name = "김철수" });
// BindingSource 설정
bindingSource.DataSource = people;
dataGridView1.DataSource = bindingSource;
// 버튼 이벤트 연결
btnAdd.Click += BtnAdd_Click;
btnDelete.Click += BtnDelete_Click;
btnSave.Click += BtnSave_Click;
// DataGridView 행 선택 시 텍스트박스 업데이트
dataGridView1.SelectionChanged += (s, e) =>
{
if (dataGridView1.CurrentRow != null && dataGridView1.CurrentRow.DataBoundItem is Person selectedPerson)
{
txtName.Text = selectedPerson.Name;
}
};
}
private void BtnAdd_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(txtName.Text))
{
people.Add(new Person { Name = txtName.Text });
bindingSource.ResetBindings(false); // 데이터 갱신
txtName.Clear();
MessageBox.Show("데이터가 추가되었습니다.", "추가 완료");
}
else
{
MessageBox.Show("이름을 입력하세요.", "입력 오류");
}
}
private void BtnDelete_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow != null && dataGridView1.CurrentRow.DataBoundItem is Person selectedPerson)
{
people.Remove(selectedPerson);
bindingSource.ResetBindings(false); // 데이터 갱신
txtName.Clear();
MessageBox.Show("데이터가 삭제되었습니다.", "삭제 완료");
}
else
{
MessageBox.Show("삭제할 데이터를 선택하세요.", "삭제 오류");
}
}
private void BtnSave_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow != null && dataGridView1.CurrentRow.DataBoundItem is Person selectedPerson)
{
selectedPerson.Name = txtName.Text;
bindingSource.ResetBindings(false); // 데이터 갱신
MessageBox.Show("데이터가 수정되었습니다.", "수정 완료");
}
else
{
MessageBox.Show("수정할 데이터를 선택하세요.", "수정 오류");
}
}
}
}
3. Form1.Designer.cs
namespace WindowsFormsApp1
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
private DataGridView dataGridView1;
private Label lblName;
private TextBox txtName;
private Button btnAdd;
private Button btnDelete;
private Button btnSave;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.dataGridView1 = new DataGridView();
this.lblName = new Label();
this.txtName = new TextBox();
this.btnAdd = new Button();
this.btnDelete = new Button();
this.btnSave = 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;
// lblName
this.lblName.AutoSize = true;
this.lblName.Location = new System.Drawing.Point(20, 230);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(50, 20);
this.lblName.TabIndex = 1;
this.lblName.Text = "이름:";
// txtName
this.txtName.Location = new System.Drawing.Point(80, 230);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(150, 27);
this.txtName.TabIndex = 2;
// btnAdd
this.btnAdd.Location = new System.Drawing.Point(20, 270);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(100, 30);
this.btnAdd.TabIndex = 3;
this.btnAdd.Text = "추가";
this.btnAdd.UseVisualStyleBackColor = true;
// btnDelete
this.btnDelete.Location = new System.Drawing.Point(140, 270);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(100, 30);
this.btnDelete.TabIndex = 4;
this.btnDelete.Text = "삭제";
this.btnDelete.UseVisualStyleBackColor = true;
// btnSave
this.btnSave.Location = new System.Drawing.Point(260, 270);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(100, 30);
this.btnSave.TabIndex = 5;
this.btnSave.Text = "저장";
this.btnSave.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, 320);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.txtName);
this.Controls.Add(this.lblName);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "데이터 바인딩 예제";
this.ResumeLayout(false);
this.PerformLayout();
}
}
}
6. 실행 결과
- 데이터 표시
- DataGridView에 초기 데이터(홍길동, 김철수)가 표시됩니다.
- 데이터 추가
- 이름을 입력하고 "추가" 버튼 클릭 → 새로운 데이터가 추가됩니다.
- 데이터 삭제
- DataGridView에서 행 선택 후 "삭제" 버튼 클릭 → 해당 데이터가 삭제됩니다.
- 데이터 수정
- DataGridView에서 행 선택 → 이름 수정 후 "저장" 버튼 클릭 → 데이터가 수정됩니다.
7. 주요 개념 요약
- BindingSource는 데이터 소스와 컨트롤 간 데이터 바인딩을 관리.
- ResetBindings(false)로 BindingSource를 갱신하여 데이터 변경 사항 반영.
- 데이터 바인딩을 활용하면 UI와 데이터 동기화를 간단히 구현 가능.
728x90