반응형
C# -- DataGridView 에 List 바인딩시, attribute 이용한, 컬럼명 변경 or 숨기기
** List 와 DataGridView 를 binding 시킨후에는, List 에 직접 data 추가하면 안됨.
--> 그냥 BindingSource.Add( ) 를 사용하면됨.
** binding 할 List data 의 class 만들때, Property 위에 Atrribute 를 적으면,
DataGridView 상에서 column 명을 바꾸거나, 해당 column 을 숨길수있다.
1.Attribute 사용전
2. Attribute 사용후
< 소스 >
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Diagnostics; | |
using System.Windows.Forms; | |
namespace datagridview_test2_attribute | |
{ | |
public partial class Form1 : Form | |
{ | |
List<Student> studentList = new List<Student>(); | |
BindingSource bindingSource = new BindingSource(); | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void Form1_Load(object sender, EventArgs e) | |
{ | |
studentList.Add(new Student("Tom", 17, 33.2, false)); | |
studentList.Add(new Student("Sara", 19, 53.4, true)); | |
studentList.Add(new Student("홍길동", 15, 130.2, false)); | |
studentList.Add(new Student("이순신", 16, 43.2, true)); | |
studentList.Add(new Student("Ace", 15, 23.2, false)); | |
this.bindingSource.DataSource = this.studentList; | |
this.dataGridView1.DataSource = bindingSource; | |
//this.dataGridView1.DataSource = this.studentList; | |
} | |
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) | |
{ | |
foreach(Student student in studentList) | |
{ | |
Debug.WriteLine(student); | |
} | |
Debug.WriteLine("----------------------------------------------------------"); | |
} | |
private void btnAdd_Click(object sender, EventArgs e) | |
{ | |
Student std = new Student("추가1", 22, 11.33, false); | |
//studentList.Add(std); // binding 후에는, List 에 바로 추가시 DataGridView 에는 반영안됨. | |
this.bindingSource.Add(std); // DataGridView 반영되고, binding 된 List 에도 추가됨. | |
} | |
} | |
class Student | |
{ | |
public string Name { get; } | |
[DisplayName("나이")] | |
public int Age { get; set; } | |
[Browsable(false)] | |
public double Weight { get; set; } | |
public bool Glass { get; set; } = false; // 안경끼면, true | |
public Student(string name, int age, double weight, bool glass) | |
{ | |
this.Name = name; | |
this.Age = age; | |
this.Weight = weight; | |
this.Glass = glass; | |
} | |
public override string ToString() | |
{ | |
return $"-- Name={Name},\t Age={Age}, 몸무게={Weight}, \t 안경착용={Glass}--"; | |
} | |
} | |
} | |
반응형
'C#' 카테고리의 다른 글
C# - 문자열 양방향 암호화 ( RijndaelManaged ) (0) | 2021.01.25 |
---|---|
C# -- HttpClient 기본 사용법 ; http, https (0) | 2021.01.01 |
C# -- popup listbox window 구현하기 (0) | 2020.09.16 |
C# -- listbox 에서 선택해제하기 (deselect) (0) | 2020.08.17 |
C# -- base64 인코딩 (0) | 2020.07.25 |