[태그:] <span>ADO.NET</span>

이번에는 DataView 개체를 사용하는 간단한 예를 살펴볼게요.

여기에서는 Books 테이블에서 특정 저자가 쓴 책들을 ISBN 순으로 정렬한 DataView 개체를 생성한 후에 새로운 DataRowView 개체를 생성하여 추가하고 기존에 있던 데이터를 변경하는 예제입니다.

먼저 Books 테이블에서 저자가 홍길동인 책들을 ISBN 순으로 정렬한 DataView 개체를 생성합니다.

DataView dv = new DataView(dt, "Author='홍길동'", "ISBN", 
                           DataViewRowState.CurrentRows);

그리고 DataView 개체에 있는 정보를 출력해 보면 Books 테이블에 있는 데이터 중에 저자가 홍길동인 책들만 ISBN 순으로 출력됨을 확인할 수 있습니다.

Console.WriteLine("※ DataView 정보");
DataRowView drv = null;
for (int i = 0; i < dv.Count; i++)
{
    drv = dv[i];
    foreach (DataColumn dc in dt.Columns)
    {
        Console.WriteLine("{0}:{1}", dc.ColumnName, drv[dc.ColumnName]);
    }
    Console.WriteLine("-------------------------------------");
}
Books 테이블과 필터링 한 DataView 개체 정보 비교
Books 테이블과 필터링 한 DataView 개체 정보 비교

DataView 개체를 이용해서 새로운 데이터를 추가할 때는 AddNew 메서드를 이용해서 DataRowView 개체를 생성합니다. 그리고 데이터를 설정후에 EndEdit 메서드를 이용하여 편집을 마감하여 의존 관계에 있는 테이블에 데이터를 추가합니다.

DataRowView drv = dv.AddNew();
drv["ISBN"] = "111-11-1111-111-9";
drv["Title"] = "C#";
drv["Author"] = "홍길동";
drv["Price"] = 1000;
drv.EndEdit();
새로운 데이터 추가 결과 화면
새로운 데이터 추가 결과 화면

DataView 개체는 인덱서를 제공하여 Items 컬렉션에 있는 DataRowView 요소를 참조할 수 있습니다.

DataRowView drv2 = dv[0];
drv2["Price"] = 20000;
기존 데이터를 변경한 결과 화면
기존 데이터를 변경한 결과 화면

이제까지 다룬 내용을 포함한 소스 코드입니다.

using System;
using System.Data;

namespace 예제_12._1_DataView_개체사용
{
    class ExUsingDataView
    {
        DataTable dt = null;

        static internal void Run()
        {
            ExUsingDataView eudv = new ExUsingDataView();
            eudv.UsingDataView();
        }
        ExUsingDataView()
        {
            dt = new DataTable("Books");
            Init();
            ViewAll();
        }
        void UsingDataView()
        {
            DataView dv = new DataView(dt, "Author='홍길동'", "ISBN", DataViewRowState.CurrentRows);
            ViewDataView(dv);
            Console.WriteLine("-------1--------");
            DataRowView drv = dv.AddNew();
            drv["ISBN"] = "111-11-1111-111-9";
            drv["Title"] = "C#";
            drv["Author"] = "홍길동";
            drv["Price"] = 1000;
            drv.EndEdit();            
            ViewAll();
            Console.WriteLine("-------2--------");
            DataRowView drv2 = dv[0];
            drv2["Price"] = 20000;
            ViewAll();
        }
        private void ViewDataView(DataView dv)
        {
            Console.WriteLine("※ DataView 정보");

            DataRowView drv = null;

            for (int i = 0; i < dv.Count; i++)
            {
                drv = dv[i];

                foreach (DataColumn dc in dt.Columns)
                {
                    Console.WriteLine("{0}:{1}", dc.ColumnName, drv[dc.ColumnName]);
                }
                Console.WriteLine("-------------------------------------");
            }
        }

        void Init()
        {
            DesignTable();

            AddBooks("111-11-1111-111-1", "ADO.NET", "홍길동¯", 12000);
            AddBooks("111-11-1141-111-1", "XML.NET", "홍길동", 12000);
            AddBooks("111-11-1112-111-1", "ASP.NET", "홍길동", 12000);
            AddBooks("111-11-1512-111-1", ".NET", "강감찬", 12000);
        }
        void AddBooks(string isbn, string title, string author, int price)
        {
            try
            {
                DataRow dr = dt.NewRow();
                dr["ISBN"] = isbn;
                dr["Title"] = title;
                dr["Author"] = author;
                dr["Price"] = price;
                dt.Rows.Add(dr);
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} 추가 실패", title);
                Console.WriteLine("이유:{0}", e.Message);
            }
        }

        void DesignTable()
        {
            DataColumn dc_title = new DataColumn();
            dc_title.ColumnName = "Title";
            dc_title.DataType = typeof(string);
            dc_title.AllowDBNull = false;
            dt.Columns.Add(dc_title);

            DataColumn dc_isbn = new DataColumn("ISBN", typeof(string));
            dc_isbn.Unique = true;
            dc_isbn.AllowDBNull = false;
            dt.Columns.Add(dc_isbn);

            DataColumn dc_author = new DataColumn();
            dc_author.ColumnName = "Author";
            dc_author.DataType = typeof(string);
            dc_author.AllowDBNull = false;
            dt.Columns.Add(dc_author);

            DataColumn dc_price = new DataColumn();
            dc_price.ColumnName = "Price";
            dc_price.DataType = typeof(int);
            dc_price.AllowDBNull = false;
            dt.Columns.Add(dc_price);
            DataColumn[] pkeys = new DataColumn[1];
            pkeys[0] = dc_isbn;
            dt.PrimaryKey = pkeys;
        }
        void ViewAll()
        {
            int row_count = dt.Rows.Count;
            Console.WriteLine("※ Books 테이블 정보");
            Console.WriteLine("테이블 명: {0}", dt.TableName);
            Console.WriteLine("테이블 명: {0}", dt.TableName);
            Console.WriteLine("행 개수:{0}", row_count);
            DataRow dr = null;
            for (int i = 0; i < row_count; i++)
            {
                dr = dt.Rows[i];
                foreach (DataColumn dc in dt.Columns)
                {
                    Console.WriteLine("{0}:{1}", dc.ColumnName, dr[dc]);
                }
                Console.WriteLine("-------------------------------------");
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ExUsingDataView.Run();
        } 
    }
}

MSSQL과 ADO.NET