본문 바로가기
C++ 200제/코딩 IT 정보

C# DataTable 예제 - Add foreach using DataGridView For 사용법

by vicddory 2019. 10. 10.

C# 데이터 테이블 예제입니다.

DataTable을 사용하여 데이터베이스 및 기타 데이터 소스의 메모리에 데이터를 저장합니다.


DataTable.

사용 방법은 다양합니다. 비슷한 의미로 컴퓨터 데이터에는 많은 행과 열이 있습니다. 데이터테이블 클래스는 데이터의 행과 열을 저장합니다.


DataTable은 c# System.Data 네임 스페이스의 일부입니다. 저장된 데이터를 추가, 선택, 반복합니다. foreach 루프는 DataTable의 행에 사용할 수 있습니다.

Type

첫 번째 프로그램입니다. 데이터는 데이터베이스, 메소드, 메모리에서 가져올 수 있습니다. 이번엔 GetTable을 활용해 서로 다른 유형의 4개 열이 있는 테이블을 생성합니다.


  • then : 테이블을 디스크에 유지, 표시, 메모리에 저장할 수 있습니다. 다른 object와 같습니다.
  • GetTable : 이 메서드는 새로운 DataTable 레퍼런스를 만듭니다. 4개 열, 5개 행 컬렉션을 추가합니다.
  • Typeof : Typeof를 사용하여 열을 생성합니다. 이 열에 있는 행의 모든 ​​필드에 존재합니다.


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
using System;
using System.Data;
 
class Program
{
    static void Main()
    {
        // Get the DataTable.
        DataTable table = GetTable();
        // ... Use the DataTable here with SQL.
    }
 
    /// <summary>
    /// This example method generates a DataTable.
    /// </summary>
    static DataTable GetTable()
    {
        // Here we create a DataTable with four columns.
        DataTable table = new DataTable();
        table.Columns.Add("Dosage"typeof(int));
        table.Columns.Add("Drug"typeof(string));
        table.Columns.Add("Patient"typeof(string));
        table.Columns.Add("Date"typeof(DateTime));
 
        // Here we add five DataRows.
        table.Rows.Add(25"Indocin""David", DateTime.Now);
        table.Rows.Add(50"Enebrel""Sam", DateTime.Now);
        table.Rows.Add(10"Hydralazine""Christoff", DateTime.Now);
        table.Rows.Add(21"Combivent""Janet", DateTime.Now);
        table.Rows.Add(100"Dilantin""Melanie", DateTime.Now);
        return table;
    }
}
cs


Method

  • Rows, Field : 데이터테이블의 모든 행을 반복합니다. 그런 다음 필드 확장 방법을 사용하여 첫 번째 필드부터 int로 액세스합니다.
  • Generic Method : 필드가 일반적인 호출 방법(Generic Method)입니다. 따라서 동작을 나타내기 위해 파라메트릭 유형 (여기서는 int)을 지정해야 합니다.
  • Rows : 종종 DataTable의 행에 액세스(요소에 엑세스하는 것과 다름)해야 합니다. 반복될 수 있는 c# Rows 속성이 이상적입니다.


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
using System;
using System.Data;
 
class Program
{
    static void Main()
    {
        // This uses the GetTable method (please paste it in).
        DataTable data = GetTable();
 
        // ... Loop over all rows.
        foreach (DataRow row in data.Rows)
        {
            // ... Write value of first field as integer.
            Console.WriteLine(row.Field<int>(0));
        }
    }
}
 
Output
 
25
50
10
21
100
cs



Example Program

  • Using : DataTable은 using문에 넣을 수 있습니다. 프로그램 성능에 도움이 될 수 있습니다. 종종 블록 구성을 사용하면 자원 관리(resource management)를 향상시키는 데 도움이 됩니다.
  • 팁1 : c# using 블록 내부(외부 아님)에서 데이터테이블 인스턴스에 열과 행을 추가 할 수 있습니다.
  • 팁2 : 이 예제에서는 Dispose 메서드가 호출됩니다. using문 다음에 DataTable의 Dispose()가 호출됩니다.
  • Dispose : Dispose가 호출되면 기본 리소스가 해제됩니다. 리소스 사용 이슈에 도움이 될 수 있습니다.


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
using System;
using System.Data;
 
class Program
{
    static void Main()
    {
        // Safely create and dispose of a DataTable.
        using (DataTable table = new DataTable())
        {
            // Two columns.
            table.Columns.Add("Name"typeof(string));
            table.Columns.Add("Date"typeof(DateTime));
 
            // ... Add two rows.
            table.Rows.Add("cat", DateTime.Now);
            table.Rows.Add("dog", DateTime.Today);
 
            // ... Display first field.
            Console.WriteLine(table.Rows[0].Field<string>(0));
        }
    }
}
 
Output
 
cat
cs


data

  • DataGridView 예제 : List와 같은 객체 컬렉션(object collection) 데이터를 DataTable에 삽입합니다. 그런 다음 Windows Forms를 사용하여 해당 테이블을 화면에 렌더링합니다. DataTable은 데이터를 표시하는데 도움이 됩니다.
  • Form : 이 코드는 Form 소스이며 DataGridView를 사용하여 Windows Forms 응용 프로그램에 배치합니다. (DataTable 생성)
  • Arrays : 2개의 c# Arrays는 클래스와 생성자에서 초기화됩니다. 여기에는 열 정보가 포함됩니다.
  • Add : DataTable에 Columns.Add를 사용하여 열 이름을 추가합니다. 열 머리글에 해당합니다.
  • Tip : 데이터테이블에는 셀에 할당 할 개체가 필요합니다. 객체는 모든 유형의 데이터를 보유할 수 있습니다.


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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// Contains column names.
        /// </summary>
        List<string> _names = new List<string>();
 
        /// <summary>
        /// Contains column data arrays.
        /// </summary>
        List<double[]> _dataArray = new List<double[]>();
 
        public Form1()
        {
            InitializeComponent();
 
            // Example column.
            _names.Add("Cat");
            // Three numbers of cat data.
            _dataArray.Add(new double[]
            {
                1.0,
                2.2,
                3.4
            });
 
            // Another example column.
            _names.Add("Dog");
            // Add three numbers of dog data.
            _dataArray.Add(new double[]
            {
                3.3,
                5.0,
                7.0
            });
            // Render the DataGridView.
            dataGridView1.DataSource = GetResultsTable();
        }
 
        /// <summary>
        /// This method builds a DataTable of the data.
        /// </summary>
        public DataTable GetResultsTable()
        {
            // Create the output table.
            DataTable d = new DataTable();
 
            // Loop through all process names.
            for (int i = 0; i < this._dataArray.Count; i++)
            {
                // The current process name.
                string name = this._names[i];
 
                // Add the program name to our columns.
                d.Columns.Add(name);
 
                // Add all of the memory numbers to an object list.
                List<object> objectNumbers = new List<object>();
 
                // Put every column's numbers in this List.
                foreach (double number in this._dataArray[i])
                {
                    objectNumbers.Add((object)number);
                }
 
                // Keep adding rows until we have enough.
                while (d.Rows.Count < objectNumbers.Count)
                {
                    d.Rows.Add();
                }
 
                // Add each item to the cells in the column.
                for (int a = 0; a < objectNumbers.Count; a++)
                {
                    d.Rows[a][i] = objectNumbers[a];
                }
            }
            return d;
        }
    }
}
cs
for
  • Compute : SUM과 함께 Compute() 메서드를 사용하여 데이터테이블의 열을 합칠 수 있습니다. 예제에선 Product 데이터 테이블을 생성하고 행 2개를 추가합니다.
  • And : 열 이름의 SUM(Varity1과 같은)으로 Compute()를 호출합니다. 필터 인수는 c# string.Empty로 지정합니다.
  • Result : Total(합계) 행에 열이 올바르게 합산된 것을 확인합니다.


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
using System;
using System.Data;
 
class Program
{
    static void Main()
    {
        var table = new DataTable();
        table.Columns.Add("Product"typeof(string));
        table.Columns.Add("Variety1"typeof(decimal));
        table.Columns.Add("Variety2"typeof(decimal));
        table.Columns.Add("Variety3"typeof(decimal));
        table.Columns.Add("Variety4"typeof(decimal));
 
        table.Rows.Add("Product 1"10121445);
        table.Rows.Add("Product 2"2015240);
 
        // Use Compute and SUM to sum up columns.
        // ... Use string.Empty as the filter as it is not needed.
        var sum1 = (decimal)table.Compute("SUM(Variety1)"string.Empty);
        var sum2 = (decimal)table.Compute("SUM(Variety2)"string.Empty);
        var sum3 = (decimal)table.Compute("SUM(Variety3)"string.Empty);
        var sum4 = (decimal)table.Compute("SUM(Variety4)"string.Empty);
        table.Rows.Add("Total", sum1, sum2, sum3, sum4);
 
        // Loop over rows.
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine(":: ROW ::");
            foreach (var item in row.ItemArray)
            {
                Console.WriteLine(item);
            }
        }
    }
}
 
Output
 
:: ROW ::
Product 1
10
12
14
45
:: ROW ::
Product 2
20
15
24
0
:: ROW ::
Total
30
27
38
45
cs



C# 관련 글

C# DataTable 행 추가 (foreach, File, DataRow 응용)

C# 엑셀 읽기 오류, MS오피스 설치 없이 데이터테이블 이용

[C# 엑셀 읽기] Microsoft.Office.Interop.Excel 참조 추가


댓글