유용한 정보

[C#] DataGridView에서 DataSource 연동하는 방법

DevReff 2025. 5. 24. 19:12
728x90
728x90
SMALL

1. 칼럼 생성 및 DataDouce와 연동되는 특성 설정하기

DataSource와 연동하기 위한 칼럼특성 설정 화면

 

    DataSource에 연결할 때 사용되는 데이터의 컬럼명을 DataPropertyName에 입력한다.

    예를들면 데이터베이스에서 로딩한 데이터를 DataTable로 수신했을 때

    그 수신된 데이터그룹의 칼럼명을 DataPropertyName에 입력하면 된다.

반응형

2. 예제

     Random rnd = new Random();
     DataTable table = new DataTable();
     DataColumn col;
     col = table.Columns.Add("CHK", typeof(bool));
     col.ReadOnly = false;
     col = table.Columns.Add("NAME", typeof(string));
     col.ReadOnly = true;
     col = table.Columns.Add("AGE", typeof(int));
     col.ReadOnly = true;
     col = table.Columns.Add("SEX", typeof(string));
     col.ReadOnly = true;
    

     for (int i = 0; i < 100; ++i)
     {
         DataRow row = table.NewRow();
         row.ItemArray = new object[]
         {
             ((rnd.Next(1, 1000) % 2) == 0),
             $"Name{(i + 1)}",
             rnd.Next(1, 100),
             ((rnd.Next(1, 1000) % 2) == 0 ? "남" : "여")
         };
         table.Rows.Add(row);
     }
     grdView.DataSource = table;

 

빨강색 사각영역은 예제소스의 결과

 

    위의 예제는 DataGridView의 칼럼 생성시 DataPropertyName을 

    첫번째 칼럼은 CHK, 이름은 NAME, 나이는 AGE, 성별은 SEX로 했고,

    DataTable의 칼럼은 각각 CHK, NAME, AGE, SEX로 되어 있다.

 

728x90
728x90
LIST