Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - Windows Forms의 데이터 바인딩 지원(DataBinding, DataSource)

WPF의 MVVM에 가려져 잘 알려지진 않았지만, Windows Form도 나름대로의 DataBinding 기능이 있습니다. 게다가 Control 타입 수준에서 제공하고 있기 때문에,

Control.DataBindings Property
; https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.databindings

WPF처럼 Windows Forms 역시 내부 구조 자체에서 MVVM과 유사한 기능을 이미 구현하고 있는 것입니다. 실제로 간단하게 테스트를 해볼까요? 다음과 같이 타입을 하나 만들고,

public class MyTitle
{
    public string Title { get; set; } = "test2";
}

이것을 TextBox를 하나 담고 있는 Windows Forms에서 다음과 같은 식으로 바인딩할 수 있습니다.

public partial class Form1 : Form
{
    MyTitle title = new MyTitle();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var myTitleBinding = new BindingSource();
        myTitleBinding.DataSource = title;

        textBox1.DataBindings.Add(new Binding("Text", myTitleBinding, "Title", true, DataSourceUpdateMode.Never));
    }
}

보시면, (TextBox 타입인) "textBox1"의 DataBindings에 MyTitle 개체를 DataSource로 담고 있는 바인딩을 연결하고 있습니다. 따라서 위의 프로그램을 실행하면 textBox1은 실행 시에 "title" 인스턴스의 "Title" 속성으로부터 값을 가져와 textBox1.Text 속성에 자동으로 값을 설정합니다. 결국 화면에는 텍스트 상자에 "test2"라는 글자가 보이게 됩니다.

당연히, title.Title 속성 값이 변경되면 자동으로 textBox1에서 그 값을 가져오는 기능도 있습니다. 이를 위해서는 값이 바뀌는 것을 인지하기 위해 MyTitle 스스로 값이 바뀌었음을 알려야 합니다.

public class MyTitle : INotifyPropertyChanged
{
    string title = "test2";

    public string Title
    {
        get { return title; }
        set
        {
            if (title == value)
            {
                return;
            }

            title = value;
            var propArg = new PropertyChangedEventArgs(nameof(Title));
            PropertyChanged?.Invoke(this, propArg);
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;
}

그리고, DataBindings의 Binding에서도 OnPropertyChanged 상태에서 값을 업데이트하겠다는 설정을 하면,

textBox1.DataBindings.Add(new Binding("Text", myTitleBinding, "Title", true, DataSourceUpdateMode.OnPropertyChanged));

이후 MyTitle 인스턴스의 값이 바뀔 때마다

private void button1_Click(object sender, EventArgs e)
{
    this.title.Title = DateTime.Now.ToString(); // 자동으로 textBox1.Text의 값도 바뀜
}

TextBox의 글자가 함께 바뀌게 됩니다. 사실상 기능면으로 보면 WPF와 다를 바 없고, 단지 WPF가 XML로 데이터 바인딩을 지정하는 기능이 더 있다는 정도가 되겠습니다.




DataGridView도, Control로부터 상속받았기 때문에 DataBindings 속성을 그대로 가지고 있습니다. 하지만, 이것 외에도 데이터를 지정할 수 있는 방법을 몇 개 더 제공하고 있습니다.

우선, DataGridView 스스로 칼럼을 지정하고 값을 설정할 수 있습니다.

private void Form1_Load(object sender, EventArgs e)
{
    this.dataGridView1.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()) { HeaderText = "idx"});
    this.dataGridView1.Columns.Add(new DataGridViewColumn(new DataGridViewTextBoxCell()) { HeaderText = "value" });

    this.dataGridView1.Rows.Add(1, "test1");
    this.dataGridView1.Rows.Add(2, "test2");
}

winform_databindings_1.png

이런 경우, 값을 변경하는 것도 단순히 Rows 속성을 통하면 됩니다.

private void button1_Click(object sender, EventArgs e)
{
    this.dataGridView1.Rows.Add("3", "test3"); // 값을 추가하고,
    this.dataGridView1.Rows.RemoveAt(0); // 값을 삭제하고.
}

또 다른 방법으로는, DataGridView에서 직접 제공하는 DataSource 속성을 이용해,

DataGridView.DataSource Property
; https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.datasource

사용자가 만든 개체를,

public class MyData
{
    public int Age { get; set; }
    public string Name { get; set; } = "";
}

직접 목록으로 전달할 수 있습니다.

MyData m1 = new MyData { Age = 30, Name = "Kevin" };
MyData m2 = new MyData { Age = 31, Name = "Winnie" };

List data = new List { m1, m2 };
// 또는, MyData[] data = new MyData[] { m1, m2 };

this.dataGridView1.DataSource = data;

그럼, GridDataView는 해당 타입을 Reflection으로 접근해 읽기 가능한 공용 (필드가 아닌) 속성을 열거해 자동으로 칼럼을 구성해 값을 보여줍니다.

winform_databindings_2.png

그런데, 이런 경우에는 후에 data 목록의 값을 변경해도 GridDataView는 그 변화를 인지하지 못합니다.

private void button1_Click(object sender, EventArgs e)
{
    List<MyData>? data = this.dataGridView1.DataSource as List<MyData>;
    data?.Add(new MyData { Age = 32, Name = "Cooper" }); // 값을 추가해도 DataGridView에는 변화 없음!
}

당연하겠죠? 이런 경우 이 글의 처음 예제에서 INotifyPropertyChanged를 구현했던 것처럼, 목록 역시 그 변화를 알리는 IBindingList.ListChanged 이벤트를 제공해야 합니다. 이를 위해 직접 IBindingList를 구현한 사용자 정의 목록 타입을 만들어도 되지만, 마이크로소프트는 이를 위한 목적으로 이미 BindingList 타입을 제공하고 있으니,

BindingList
; https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.bindinglist-1

이것을 이용해 구현하시면 됩니다.

private void Form1_Load(object sender, EventArgs e)
{
    MyData m1 = new MyData { Age = 30, Name = "Kevin" };
    MyData m2 = new MyData { Age = 31, Name = "Winnie" };

    BindingList<MyData> data = new BindingList<MyData>() { m1, m2 };
    this.dataGridView1.DataSource = data;
}

private void button1_Click(object sender, EventArgs e)
{
    BindingList<MyData>? data = this.dataGridView1.DataSource as BindingList<MyData>;
    data?.Add(new MyData { Age = 32, Name = "Cooper" }); // 추가된 값이 DataGridView에도 반영됨
}

혹은, Control.DataBindings가 그랬던 것처럼 BindingSource를 이용해 경유하는 것도 가능합니다.

private void Form1_Load(object sender, EventArgs e)
{
    MyData m1 = new MyData { Age = 30, Name = "Kevin" };
    MyData m2 = new MyData { Age = 31, Name = "Winnie" };

    BindingList<MyData> data = new BindingList<MyData>() { m1, m2 };

    var dataBindingSource = new BindingSource();
    dataBindingSource.DataSource = data;

    this.dataGridView1.DataSource = dataBindingSource;
}

private void button1_Click(object sender, EventArgs e)
{
    BindingSource? src = this.dataGridView1.DataSource as BindingSource;
    if (src == null)
    {
        return;
    }

    BindingList<MyData>? data = src.DataSource as BindingList<MyData>;
    data?.Add(new MyData { Age = 32, Name = "Cooper" });
}




마이크로소프트는 범용 데이터 컨테이너인 DataTable/DataSet에 대한 연동도 빼놓지 않고 있습니다.

DataTable _dt = new DataTable();

private void Form1_Load(object sender, EventArgs e)
{
    _dt.Columns.Add("idx");
    _dt.Columns.Add("value");
    _dt.Rows.Add(1, "test1");
    _dt.Rows.Add(2, "test2");

    this.dataGridView1.DataSource = _dt;
}

private void button1_Click(object sender, EventArgs e)
{
    _dt.Rows.Add(3, "test3"); // 추가된 값이 DataGridView에 즉각 반영
}

여기서 재미있는 것은, DataTable의 경우 BindingList와는 달리 IBindingList 인터페이스를 구현한 개체가 아니라는 점입니다. 그래도 저렇게 (button1_Click에서) 데이터를 추가해도 DataGridView에 즉각 반영되는 것은, IListSource를 구현하면서 그것의 GetList 메서드에서 IBindingList를 구현한 DataView 타입으로 감싼 타입을 활용하기 때문입니다.

마지막으로, 다중 테이블을 담고 있는 DataSet의 경우에는 위의 코드에서 DataTable을 구분 지을 수 있는 값을 DataMember에 지정하면 됩니다.

DataSet _ds = new DataSet();

private void Form1_Load(object sender, EventArgs e)
{
    DataTable dt1 = new DataTable("List");
    dt1.Columns.Add("idx");
    dt1.Columns.Add("value");
    dt1.Rows.Add(1, "test1");
    dt1.Rows.Add(2, "test2");

    DataTable dt2 = new DataTable("Person");
    dt2.Columns.Add("age");
    dt2.Columns.Add("name");
    dt2.Rows.Add(30, "Kevin");
    dt2.Rows.Add(31, "Winnie");

    _ds = new DataSet();
    _ds.Tables.Add(dt1);
    _ds.Tables.Add(dt2);

    var dataBindingSource = new BindingSource();
    dataBindingSource.DataSource = _ds;
    dataBindingSource.DataMember = "Person";

    this.dataGridView1.DataSource = dataBindingSource;
}

private void button1_Click(object sender, EventArgs e)
{
    _ds.Tables[1].Rows.Add(32, "Cooper");
}

이 정도면, 대충 설명이 되었겠죠? ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/3/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2023-01-17 11시39분
[성태형 사랑해요] 성태형님 친절한 설명 감사합니다!
[guest]
2023-01-18 09시11분
[gwise] DataGridView에 List받아와서 DT로 변환해서 사용하고 있는데 BindingList이걸 테스트 해 봐야 겠습니다.
그래도 DataTable를 사용하는 이유는 UI에서 RowState를 구분해서 Add/Modi/Delete 별로 데이터를 처리 하기 때문에 어쩔수(?)없이 DataTable를
사용하는데 BindingList에도 row단위로 RowState같은게 있는지 찾아 보겠습니다.
만약 1000 row에서 사용자가 수정한게 10 row면 10개만 필터로 걸러서 서버로 보냅니다. 이게 안되면 전체 데이터를 다 서버로 보내야 해서...
[guest]

1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13768정성태10/15/20245407C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/20244782오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/20244560C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/20245271오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/20245638Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/20244988Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/20245015Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/20244917오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
13760정성태10/11/20245461Linux: 82. Ubuntu - clang 최신(stable) 버전 설치
13759정성태10/10/20246372C/C++: 177. C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function) [6]
13758정성태10/8/20245579오류 유형: 926. dotnet tools를 sudo로 실행하는 경우 command not found
13757정성태10/8/20245532닷넷: 2306. Linux - dotnet tool의 설치 디렉터리가 PATH 환경변수에 자동 등록이 되는 이유
13756정성태10/8/20245633오류 유형: 925. ssh로 docker 접근을 할 때 "... malformed HTTP status code ..." 오류 발생
13755정성태10/7/20246029닷넷: 2305. C# 13 - (9) 메서드 바인딩의 우선순위를 지정하는 OverloadResolutionPriority 특성 도입 (Overload resolution priority)파일 다운로드1
13754정성태10/4/20245583닷넷: 2304. C# 13 - (8) 부분 메서드 정의를 속성 및 인덱서에도 확대파일 다운로드1
13753정성태10/4/20245596Linux: 81. Linux - PATH 환경변수의 적용 규칙
13752정성태10/2/20246292닷넷: 2303. C# 13 - (7) ref struct의 interface 상속 및 제네릭 제약으로 사용 가능 [6]파일 다운로드1
13751정성태10/2/20245413C/C++: 176. C/C++ - ARM64로 포팅할 때 유의할 점
13750정성태10/1/20245295C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계
13749정성태9/30/20245547닷넷: 2302. C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동파일 다운로드1
13748정성태9/29/20245746닷넷: 2301. C# - BigInteger 타입이 byte 배열로 직렬화하는 방식
13747정성태9/28/20245597닷넷: 2300. C# - OpenSSH의 공개키 파일에 대한 "BEGIN OPENSSH PUBLIC KEY" / "END OPENSSH PUBLIC KEY" PEM 포맷파일 다운로드1
13746정성태9/28/20245696오류 유형: 924. Python - LocalProtocolError("Illegal header value ...")
13745정성태9/28/20245559Linux: 80. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (lldb)
13744정성태9/27/20245995닷넷: 2299. C# - Windows Hello 사용자 인증 다이얼로그 표시하기파일 다운로드1
13743정성태9/26/20246434닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법 [1]
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...