Last active
October 30, 2020 04:25
-
-
Save jayu108/463fa5ead1fcfb371a9748118815a150 to your computer and use it in GitHub Desktop.
C# -- DataGridView 와 List 연동시, data class 의 property 에 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}--"; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment