[C# 문법] C# DataTable 에서 ColumnName(컬럼이름) 얻어오는 방법



안녕하세요.

 

오늘은 C# 문법에서 DataTable에서 컬럼 이름을 얻어오는 방법에 대해서 알려드리려고 합니다.

 

어려운 구문이 아니기 때문에, 다른 설명 없이 예제 코드를 통해서 바로 알려드리도록 하겠습니다.


 

Student와 관련된 DataTable을 만들어서 여기서 생성한 컬럼들을 리스트로 얻어와서 출력하는 예제코드를 작성해 보도록 하겠습니다.

 

예제 코드


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace test123

{

    class Program

    {

        static void Main(string[] args)

        {

            //  DataTable dt = new DataTable("Branches");  

            DataTable dt = new DataTable("Student");

            dt.Columns.Add("StudentId"typeof(Int32));

            dt.Columns.Add("StudentName"typeof(string));

            dt.Columns.Add("Address"typeof(string));

            dt.Columns.Add("MobileNo"typeof(string));

 

            //Data  

            dt.Rows.Add(1"Manish""Hyderabad""0000000000");

            dt.Rows.Add(2"Venkat""Hyderabad""111111111");

            dt.Rows.Add(3"Namit""Pune""1222222222");

            dt.Rows.Add(4"Abhinav""Bhagalpur""3333333333");

 

            List<string> colNameList = new List<string>();

 

            //중복된 List 빼고 저장

            colNameList = GetColumnName(dt).Distinct().ToList();

 

            //DataTable에서 저정되어 있는 컬럼 이름 출력하기

            foreach(var str in colNameList)

            {

                Console.WriteLine("컬럼 이름 : {0}", str.ToString());

            }

        }

 

        /// <summary>

        /// DataTable에서 컬럼 이름 얻어오는 메서드

        /// </summary>

        /// <param name="ds"></param>

        /// <returns></returns>

        private static List<string> GetColumnName(DataTable dt)

        {

            List<string> list = new List<string>();

            string ColumnName = string.Empty;

 

            foreach (DataRow row in dt.Rows)

            {

                foreach (DataColumn column in dt.Columns)

                {

                    ColumnName = column.ColumnName;

                    list.Add(ColumnName);

                }

            }

 

            return list;

        }

    }

}

 

Colored by Color Scripter

cs

 

실행 결과



위와 같이, 제가 임시로 만든 DataTable에 저장한 컬럼들인 StudentId, StudentName, Address, MobileNo 4개의 컬럼들의 정보를 가져와서 알맞게 출력된 것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY