반응형

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 사용후







< 소스 >


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}--";
}
}
}


반응형
Posted by 자유프로그램
,