[C# 윈폼] 윈폼 XML 파일 읽고 해당 데이터 DataGridView에 보여주기

안녕하세요.

 

오늘은 C# 윈폼에서 XML 파일 다루는 방법에 대해서 알아보려고 합니다.

 

간단하게 윈폼에서 XML 파일을 읽어와 해당 내용을 파싱하고, 파싱된 데이터를 최종적으로 DataGridView 컨트롤에 바인딩하여 데이터를 보여주는 예제 프로그램을 만들어 보도록 하겠습니다.

 

그럼 바로 예제 코드를 작성해 보도록 하겠습니다.

 

먼저 빈 윈폼 프로젝트를 생성해 주시고 아래와 같이 TextBox, Button, DataGridView 컨트롤을 배치해 주시기 바랍니다.

 

윈폼 프로젝트 생성 및 각종 컨트롤 배치

 위와 같이 TableLayoutPanel, Pane, Textbox, Button, DataGridView 컨트롤을 이용해서 UI 배치를 진행하였습니다.

 

이제 아래와 같이 Student 테스트 XML 파일을 작성해 주시기 바랍니다.

 

STUDENT XML 파일 내용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<STUDENT>
    <STD_INFO>
        <STD_NAME>범범조조</STD_NAME>
        <STD_AGE>21</STD_AGE>
        <STD_GRADE>A+</STD_GRADE>
        <STD_MAJOR>컴퓨터공학부</STD_MAJOR>
    </STD_INFO>
    <STD_INFO>
        <STD_NAME>아이유</STD_NAME>
        <STD_AGE>23</STD_AGE>
        <STD_GRADE>B+</STD_GRADE>
        <STD_MAJOR>경영학과</STD_MAJOR>
    </STD_INFO>
    <STD_INFO>
        <STD_NAME>유재석</STD_NAME>
        <STD_AGE>26</STD_AGE>
        <STD_GRADE>A</STD_GRADE>
        <STD_MAJOR>국어교육과</STD_MAJOR>
    </STD_INFO>
</STUDENT>
cs

위와 같이 STUDENT XML 파일을 작성 하였다면, 이제 위에서 껍데기 UI 를 만들었던 프로젝트의 비하인드 코드 부분을 작성해 보도록 하겠습니다.

 

Main.cs
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace XML_Parser
{
    public partial class Form1 : Form
    {
        public List<Student> stuList = new List<Student>();
 
        public Form1()
        {
            InitializeComponent();
 
            //이벤트 선언
            InitEvent();
        }
 
        /// <summary>
        /// 각종 이벤트 선언 메서드
        /// </summary>
        private void InitEvent()
        {
            this.Load += MainForm_Load;
            this.uiBtn_Load.Click += uiBtn_Load_Click;
            this.uiBtn_Parse.Click += uiBtn_Parse_Click;
        }
 
        private void MainForm_Load(object sender, EventArgs e)
        {
            Data_View_Design();
        }
 
        private void uiBtn_Load_Click(object sender, EventArgs e)
        {
            GetOpenFile();
        }
 
        private void uiBtn_Parse_Click(object sender, EventArgs e)
        {
            string fileName = uiTxt_FileName.Text;
 
            if (File.Exists(fileName) == false)
            {
                MessageBox.Show("File does not exist.""Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
 
            DataSet xmlDs = new DataSet();
 
            try
            {
                // XML File -> DataSet
                xmlDs.ReadXml(fileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
 
            if (xmlDs != null && xmlDs.Tables.Count > 0 && xmlDs.Tables[0].Rows.Count > 0)
            {
                //DataView Binding
                uiDGV_Main.DataSource = GetDataTable(xmlDs);
            }
        }
 
        /// <summary>
        /// DataTable 생성
        /// </summary>
        /// <returns></returns>
        private DataTable GetDataTable(DataSet ds)
        {
            return ds.Tables[0];
        }
 
        /// <summary>
        /// OpenFileDialog 메서드
        /// </summary>
        private void GetOpenFile()
        {
            OpenFileDialog ofd = new OpenFileDialog
            {
                Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*",
                Title = "XML 파일 예제창"
            };
 
            if (ofd.ShowDialog() == DialogResult.OK)
                uiTxt_FileName.Text = ofd.FileName;
        }
 
        /// <summary>
        /// DataGridView 사이즈 조절
        /// </summary>
        private void Data_View_Design()
        {
            try
            {
                uiDGV_Main.AutoGenerateColumns = true;
                //DataGridView 사이즈에 맞게 자동 조정
                uiDGV_Main.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                this.uiDGV_Main.EditMode = DataGridViewEditMode.EditOnEnter;
 
                //DataGridView 일반 Row열 디자인
                uiDGV_Main.BorderStyle = BorderStyle.None;
                uiDGV_Main.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(238239249);
                uiDGV_Main.CellBorderStyle = DataGridViewCellBorderStyle.Single;
                uiDGV_Main.DefaultCellStyle.Font = new Font("굴림"11, FontStyle.Bold);
 
                //Row 오른쪽 정렬
                uiDGV_Main.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                uiDGV_Main.DefaultCellStyle.SelectionBackColor = Color.LightSkyBlue;
                uiDGV_Main.DefaultCellStyle.SelectionForeColor = Color.WhiteSmoke;
                uiDGV_Main.BackgroundColor = Color.White;
 
                //DataGridView ColumnHeader 디자인
                uiDGV_Main.EnableHeadersVisualStyles = false;
                uiDGV_Main.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
                uiDGV_Main.ColumnHeadersDefaultCellStyle.Font = new Font("굴림"11, FontStyle.Bold);
 
                //dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(15, 50, 72);
                uiDGV_Main.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(155072);
 
                //Header Colunm 오른쪽 정렬
                uiDGV_Main.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                uiDGV_Main.ColumnHeadersDefaultCellStyle.ForeColor = Color.White; //컬럼명 폰트 컬러
 
                //DataGridView RowHeader 디자인
                //dataGridView.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(15, 50, 72);
                uiDGV_Main.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(155072);
                uiDGV_Main.RowHeadersDefaultCellStyle.Font = new Font("굴림"11, FontStyle.Bold);
                uiDGV_Main.RowHeadersDefaultCellStyle.ForeColor = Color.White;// 로우명 폰트 컬러
                uiDGV_Main.RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
 
cs

 

실행 결과

 

위와 같이 STUDENT XML의 데이터를 알맞게 읽어와서 DataGirdView 컨트롤에 제대로 보여주고 있는것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY