Microsoft MVP성태의 닷넷 이야기
.NET Framework: 940. C# - Windows Forms ListView와 DataGridView의 예제 코드 [링크 복사], [링크+제목 복사]
조회: 9998
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - Windows Forms ListView와 DataGridView의 예제 코드

단일 필드를 보여줄 때 보통 ListBox를 사용하지만, 다중 필드의 경우에는 ListViewDataGridView를 선택하게 됩니다. 또한 그 2개의 주요 차이점은 해당 필드를 편집할 수 있느냐에 대한 여부로 나뉩니다. (참고로 ListView도 "LabelEdit" 속성을 통해 첫 번째 필드에 대한 값 편집은 할 수 있습니다.)

그냥 간략하게 예제 코드 차원에서 작성해 봤으니,

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<Person> list = new List<Person>();

            list.Add(new Person("t1", 5, "on t1", true));
            list.Add(new Person("t2", 6, "on t2", false));
            list.Add(new Person("t3", 7, "on t3", true));
            list.Add(new Person("t4", 8, "on t4", false));
            list.Add(new Person("t5", 9, "on t5", true));

            SetupListView(list);
            SetupDataGridView(list);
        }

        private void SetupListView(List<Person> list)
        {
            this.listView1.View = System.Windows.Forms.View.Details;
            this.listView1.CheckBoxes = true;
            // this.LabelEdit = true;

            ColumnHeader ch = new ColumnHeader()
            {
                Text = nameof(Person.Name),
                Width = 50
            };
            this.listView1.Columns.Add(ch);

            ch = new ColumnHeader()
            {
                Text = nameof(Person.Age),
                Width = 50
            };
            this.listView1.Columns.Add(ch);

            ch = new ColumnHeader()
            {
                Text = nameof(Person.Address),
                Width = 120,
            };
            this.listView1.Columns.Add(ch);

            ch = new ColumnHeader()
            {
                Text = nameof(Person.IsMale),
                Width = 50,
            };
            this.listView1.Columns.Add(ch);

            FillListView(list);
        }

        private void FillListView(List<Person> list)
        {
            this.listView1.Items.Clear();

            foreach (Person person in list)
            {
                ListViewItem item = new ListViewItem();

                item.Text = person.Name;

                {
                    System.Windows.Forms.ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                    subItem.Text = person.Age.ToString();
                    item.SubItems.Add(subItem);
                }

                {
                    System.Windows.Forms.ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                    subItem.Text = person.Address;
                    item.SubItems.Add(subItem);
                }

                {
                    System.Windows.Forms.ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                    subItem.Text = person.IsMale.ToString();
                    item.SubItems.Add(subItem);
                }

                this.listView1.Items.Add(item);
            }
        }

        private void SetupDataGridView(List<Person> list)
        {
            this.dataGridView1.ColumnCount = 3;

            DataGridViewCheckBoxColumn col0 = new DataGridViewCheckBoxColumn();
            col0.Name = "";
            col0.Width = 25;
            this.dataGridView1.Columns.Insert(0, col0);

            this.dataGridView1.Columns[1].Name = "Name";
            this.dataGridView1.Columns[1].Width = 50;

            this.dataGridView1.Columns[2].Name = "Age";
            this.dataGridView1.Columns[2].Width = 50;
            this.dataGridView1.Columns[2].ReadOnly = true;

            this.dataGridView1.Columns[3].Name = "Address";
            this.dataGridView1.Columns[3].Width = 120;

            DataGridViewCheckBoxColumn col4 = new DataGridViewCheckBoxColumn();
            col4.Name = "IsMale";
            col4.Width = 50;
            col4.ReadOnly = true;
            this.dataGridView1.Columns.Add(col4);

            FillDataGridView(list);
        }

        private void FillDataGridView(List<Person> list)
        {
            this.dataGridView1.Rows.Clear();

            foreach (Person person in list)
            {
                this.dataGridView1.Rows.Add(person.Values());
            }
        }
    }

    public class Person
    {
        public string Name;
        public int Age;
        public string Address;
        public bool IsMale;

        public Person(string name, int age, string address, bool isMale)
        {
            Name = name;
            Age = age;
            Address = address;
            IsMale = isMale;
        }

        public string [] Values()
        {
            return new string[]
            {
                false.ToString(), Name, Age.ToString(), Address, IsMale.ToString()
            };
        }
    }
}

참고하시고, 아래는 위의 프로그램에 대한 실행 화면으로 왼쪽은 ListView, 오른쪽은 DataGridView를 보여줍니다.

listview_vs_datagridview_1.png

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 9/19/2020]

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

비밀번호

댓글 작성자
 




... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13194정성태12/14/20225003오류 유형: 833. warning C4747: Calling managed 'DllMain': Managed code may not be run under loader lock파일 다운로드1
13193정성태12/14/20225055오류 유형: 832. error C7681: two-phase name lookup is not supported for C++/CLI or C++/CX; use /Zc:twoPhase-
13192정성태12/13/20225057Linux: 55. 리눅스 - bash shell에서 실수 연산
13191정성태12/11/20225959.NET Framework: 2077. C# - 직접 만들어 보는 SynchronizationContext파일 다운로드1
13190정성태12/9/20226434.NET Framework: 2076. C# - SynchronizationContext 기본 사용법파일 다운로드1
13189정성태12/9/20227046오류 유형: 831. Visual Studio - Windows Forms 디자이너의 도구 상자에 컨트롤이 보이지 않는 문제
13188정성태12/9/20225902.NET Framework: 2075. C# - 직접 만들어 보는 TaskScheduler 실습 (SingleThreadTaskScheduler)파일 다운로드1
13187정성태12/8/20225832개발 환경 구성: 654. openssl - CA로부터 인증받은 새로운 인증서를 생성하는 방법 (2)
13186정성태12/6/20224367오류 유형: 831. The framework 'Microsoft.AspNetCore.App', version '...' was not found.
13185정성태12/6/20225345개발 환경 구성: 653. Windows 환경에서의 Hello World x64 어셈블리 예제 (NASM 버전)
13184정성태12/5/20224652개발 환경 구성: 652. ml64.exe와 link.exe x64 실행 환경 구성
13183정성태12/4/20224495오류 유형: 830. MASM + CRT 함수를 사용하는 경우 발생하는 컴파일 오류 정리
13182정성태12/4/20225198Windows: 217. Windows 환경에서의 Hello World x64 어셈블리 예제 (MASM 버전)
13181정성태12/3/20224601Linux: 54. 리눅스/WSL - hello world 어셈블리 코드 x86/x64 (nasm)
13180정성태12/2/20224838.NET Framework: 2074. C# - 스택 메모리에 대한 여유 공간 확인하는 방법파일 다운로드1
13179정성태12/2/20224257Windows: 216. Windows 11 - 22H2 업데이트 이후 Terminal 대신 cmd 창이 뜨는 경우
13178정성태12/1/20224734Windows: 215. Win32 API 금지된 함수 - IsBadXxxPtr 유의 함수들이 안전하지 않은 이유파일 다운로드1
13177정성태11/30/20225427오류 유형: 829. uwsgi 설치 시 fatal error: Python.h: No such file or directory
13176정성태11/29/20224382오류 유형: 828. gunicorn - ModuleNotFoundError: No module named 'flask'
13175정성태11/29/20225929오류 유형: 827. Python - ImportError: cannot import name 'html5lib' from 'pip._vendor'
13174정성태11/28/20224568.NET Framework: 2073. C# - VMMap처럼 스택 메모리의 reserve/guard/commit 상태 출력파일 다운로드1
13173정성태11/27/20225240.NET Framework: 2072. 닷넷 응용 프로그램의 스레드 스택 크기 변경
13172정성태11/25/20225094.NET Framework: 2071. 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법파일 다운로드1
13171정성태11/25/20224678Windows: 214. 윈도우 - 스레드 스택의 "red zone"
13170정성태11/24/20224979Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20225593Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...