[C# 윈폼] C# XML 파싱 후, XML 데이터 MSSQL 테이블에 저장하기

안녕하세요.

 

오늘은 C# 윈폼에서 XML 파싱 후, XML 데이터를 MSSQL 데이터베이스에 한 테이블에 저장하는 방법에 대해서 알려 드리려고 합니다.

 

이전에, XML 파싱 해서 해당 데이터를 DataGridView 컨트롤에 데이터바인딩 해서 보여주는 방법에 대해서 글을 포스팅 한적이 있었는데요.

 

그 포스팅에서 조금 더 응용하여 DB 연동까지 추가해서 XML 데이터를 DB에 저장시키는 방법도 소스코드로 어떻게 하는지 보여 드리도록 하겠습니다.

 

이전 XML 관련 포스팅

2020/12/15 - [C#/Windows Form] - [C# 윈폼] 윈폼 XML 파일 읽고 해당 데이터 DataGridView에 보여주기

 

다른 부연 설명은 없이 소스코드로 보여드린다는 점 참고해 주세요!

 

그럼 아래와 같이 먼저 빈 윈폼 프로젝트를 생성해 주시고 아래와 같이 각종 컨트롤들을 배치해 주시기 바랍니다.

 

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

 

위와 같이 Label, TextBox, Button, DataGridView 컨트롤을 배치해 주시기 바랍니다.

 

그리고 나서 이제 아래와 같이 여러가지의 클래스들이 필요한데요.

 

하나씩 생성해서 해당 소스코드를 그대로 따라 작성해 주시기 바랍니다.

 

 

Config.ini
1
2
3
4
5
6
 
[DATABASE]
IP=DESKTOP-OC6SJV6\BEOMBEOMJOJO
USER=test
PWD=1234
DB_NAME=BEOMBEOMJOJO
cs

ini 파일은 데이터베이스 접속 연결에 필요한 정보를 사전에 미리 정의해서 해당 내용을 읽어서 그 내용을 이용하려고 만든 파일입니다.

 

해당 파일은 만드시고 “속성” 에서 필히 출력 디렉터리에 복사를 “항상 복사” 로 설정해 주셔야 합니다!!

 

FileManager.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
using System;
using System.Runtime.InteropServices;
using System.Text;
 
namespace XML_Parser
{
    public delegate void UpdateConfigEventHandler();
 
    public class FileManager
    {
        public static String FileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }
 
        private static String _fileName = String.Empty;
 
        /// <summary>
        /// 파일 내 특정 key 에 해당하는 value 를 읽어서 반환하는 메서드
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="def"></param>
        /// <param name="retval"></param>
        /// <param name="size"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileString(String section, String key, String def, StringBuilder retval, int size, String filePath);
 
        /// <summary>
        /// 파일 내 특정 key 에 해당하는 value 에 값을 저장하는 메서드
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        private static extern long WritePrivateProfileString(String section, String key, String val, String filePath);
 
        /// <summary>
        /// GetPrivateProfileString() 메서드를 호출하는 메서드
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public static String GetValueString(String section, String key, String defValue)
        {
            StringBuilder temp = new StringBuilder(255);
            GetPrivateProfileString(section, key, defValue, temp, 255, _fileName);
            return temp.ToString();
        }
 
        /// <summary>
        /// WritePrivateProfileString() 메서드를 호출하는 메서드
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public static long SetValue(String Section, String Key, String Value)
        {
            long result = WritePrivateProfileString(Section, Key, Value, _fileName);
            return result;
        }
 
        /// <summary>
        /// 사용하지 않는 메서드
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="defValue"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String GetValueString(String section, String key, String defValue, String filePath)
        {
            StringBuilder temp = new StringBuilder(255);
            GetPrivateProfileString(section, key, defValue, temp, 255, filePath);
            return temp.ToString();
        }
 
        /// <summary>
        /// 사용하지 않는 메서드
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static long SetValue(String Section, String Key, String Value, String filePath)
        {
            long result = WritePrivateProfileString(Section, Key, Value, filePath);
            return result;
        }
    }
}
 
 
cs

이 클래스는 Config.ini 파일의 내용을 읽어서 그 내용을 다룰 수 있게 해주는 클래스입니다.

 

MssqlManager.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
using System;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
 
namespace XML_Parser
{
    public sealed class MssqlManager
    {
        private enum ExcuteResult { Fail = -2, Success = -1 };
 
        public string ConnectionString = string.Empty;
 
        public string IP { get; private set; }
        public string LastException { get; private set; }
 
        public SqlConnection Connection { get; private set; }
 
        private static MssqlManager instance;
 
        public static MssqlManager Instance
        {
            get
            {
                if (instance == null) instance = new MssqlManager();
 
                return instance;
            }
        }
 
        private SqlCommand _sqlCmd = null;
 
        public MssqlManager()
        {
            _sqlCmd = new SqlCommand();
        }
 
        public bool GetConnection()
        {
            try
            {
                if (ConnectionString == string.Empty)
                    SetConnectionString();
 
                Connection = new SqlConnection(ConnectionString);
 
                Connection.Open();
            }
            catch (Exception ex)
            {
                LastException = ex.ToString();
 
                return false;
            }
 
            if (Connection.State == ConnectionState.Open)
                return true;
            else
                return false;
        }
 
        public int ExecuteNonQuery(string query)
        {
            lock (this)
            {
                return Execute_NonQuery(query);
            }
        }
 
        public bool HasRows(string query)
        {
            lock (this)
            {
                SqlDataReader result = ExecuteReader(query);
 
                return result.HasRows;
            }
        }
 
        public SqlDataReader ExecuteReaderQuery(string query)
        {
            lock (this)
            {
                SqlDataReader result = ExecuteReader(query);
 
                return result;
            }
        }
 
        public DataSet ExecuteDsQuery(DataSet ds, string query)
        {
            ds.Reset();
 
            lock (this)
            {
                //dbLoger.WriteLog(LogType.Inform, string.Format("ExecuteDsQuery - {0}", query));
 
                return ExecuteDataAdt(ds, query);
            }
        }
 
        public DataSet ExecuteProcedure(DataSet ds, string procName, params string[] pValues)
        {
            lock (this)
            {
                return ExecuteProcedureAdt(ds, procName, pValues);
            }
        }
 
        public void CancelQuery()
        {
            _sqlCmd.Cancel();
        }
 
        public void Close()
        {
            Connection.Close();
        }
 
        #region private..........................................................
 
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
 
        private bool CheckConnection()
        {
            bool result = true;
 
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
            {
                this.LastException = "네트워크 연결이 끊어졌습니다.";
                System.Windows.Forms.MessageBox.Show(this.LastException, "Error");
                result = false;
            }
            else if (this.Connection == null || this.Connection.State == ConnectionState.Closed)
            {
                result = this.GetConnection();
            }
 
            return result;
        }
 
        private void SetConnectionString()
        {
            string ip = FileManager.GetValueString("DATABASE""IP""");
            string user = FileManager.GetValueString("DATABASE""USER""");
            string pwd = FileManager.GetValueString("DATABASE""PWD""");
            string dbName = FileManager.GetValueString("DATABASE""DB_NAME""");
 
            string dataSource = string.Format(@"Data Source={0};Database={1};User Id={2};Password={3}", ip, dbName, user, pwd);
 
            this.IP = ip;
            this.ConnectionString = dataSource;
        }
 
        private int Execute_NonQuery(string query)
        {
            int result = (int)ExcuteResult.Fail;
 
            try
            {
                _sqlCmd = new SqlCommand
                {
                    Connection = this.Connection,
                    CommandText = query
                };
                result = _sqlCmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                LastException = ex.ToString();
 
                if (CheckConnection() == false)
                    return result;
            }
 
            return result;
        }
 
        private SqlDataReader ExecuteReader(string query)
        {
            SqlDataReader result = null;
 
            try
            {
                _sqlCmd = new SqlCommand
                {
                    Connection = this.Connection,
                    CommandText = query
                };
                result = _sqlCmd.ExecuteReader();
            }
            catch (Exception ex)
            {
                LastException = ex.ToString();
 
                if (CheckConnection() == false)
                    return result;
            }
 
            return result;
        }
 
        private DataSet ExecuteDataAdt(DataSet ds, string query)
        {
            try
            {
                SqlDataAdapter cmd = new SqlDataAdapter
                {
                    SelectCommand = _sqlCmd
                };
                cmd.SelectCommand.Connection = this.Connection;
                cmd.SelectCommand.CommandText = query;
                cmd.Fill(ds);
            }
            catch (Exception ex)
            {
                LastException = ex.Message.ToString();
 
                if (CheckConnection() == false)
                    return null;
            }
 
            return ds;
        }
 
        private DataSet ExecuteProcedureAdt(DataSet ds, string query, params string[] values)
        {
            try
            {
                SqlDataAdapter adapter = new SqlDataAdapter
                {
                    SelectCommand = _sqlCmd
                };
                adapter.SelectCommand.CommandText = query;
                adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
                adapter.SelectCommand.Connection = this.Connection;
 
                for (int i = 0; i < values.Length; ++i)
                {
                    adapter.SelectCommand.Parameters.Add(values[i]);
                    //adapter.SelectCommand.Parameters.Add("params", values[i]);
                }
 
                adapter.Fill(ds);
 
                return ds;
            }
            catch (Exception ex)
            {
                this.LastException = ex.ToString();
 
                if (CheckConnection() == false)
                    return null;
            }
 
            return ds;
        }
 
        #endregion private..................................................................
    }
}
 
 
cs

이 클래스는 DB 연결에 필요한 내용을 정의한 클래스 입니다. 참고로 데이터베이스는 MSSQL을 이용하였습니다.

 

Program.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace XML_Parser
{
    static class Program
    {
        /// <summary>
        /// 해당 애플리케이션의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // Config
            string configFile = "Config.ini";
            FileManager.FileName = $"{Environment.CurrentDirectory}\\{configFile}";
 
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
 
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
 
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
 
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
 
cs

프로그램 처음 만들 때 자동으로 생성되는 클래스이면서, 여기서 사전에 Config.ini 파일의 내용을 읽어올 예정 입니다.

 

Singleton.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
using System;
 
namespace XML_Parser
{
    public class Singleton<T> where T : classnew()
    {
        private static readonly object _syncobj = new object();
        private static volatile T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncobj)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }
 
        public delegate void ExceptionEventHandler(string LocationID, Exception ex);
    }
}
 
cs

DB 연결은 단일체 패턴을 사용하여 객체를 다룰것이라서 그거에 필요한 내용을 정의한 클래스 입니다.

 

Student.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace XML_Parser
{
    public class Student
    {
        /// <summary>
        /// 학생 이름
        /// </summary>
        public string Name { get; set; }
 
        /// <summary>
        /// 학생 나이
        /// </summary>
        public int Age { get; set; }
 
        /// <summary>
        /// 학생 성적
        /// </summary>
        public string Grade { get; set; }
 
        /// <summary>
        /// 학생 학과
        /// </summary>
        public string Major { get; set; }
    }
}
 
cs

학생의 정보를 정의한 클래스 입니다.

 

MainForm.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
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;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace XML_Parser
{
    public partial class Form1 : Form
    {
        public List<Student> stuList = new List<Student>();
 
        //Connect to DB
        private BackgroundWorker ConnectWorker = null;
 
 
        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;
            this.uiBtn_Insert.Click += uiBtn_Insert_Click;
        }
 
        private void MainForm_Load(object sender, EventArgs e)
        {
            ConnectDB();
            Data_View_Design();
        }
 
        private void uiBtn_Load_Click(object sender, EventArgs e)
        {
            GetOpenFile();
        }
 
        /// <summary>
        /// Connect to DB 
        /// </summary>
        private void ConnectDB()
        {
            if (this.ConnectWorker == null)
            {
                this.ConnectWorker = new BackgroundWorker();
                this.ConnectWorker.DoWork += ConnectWorker_DoWork;
                this.ConnectWorker.RunWorkerCompleted += ConnectWorker_RunWorkerCompleted;
            }
 
            this.ConnectWorker.RunWorkerAsync();
        }
 
        /// <summary>
        /// Try to connect DB
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConnectWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                    if (MssqlManager.Instance.GetConnection() == true)
                        break;
 
                    Thread.Sleep(1000);
                }
                catch { }
            }
        }
 
        private void ConnectWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            uiBtn_Parse.Invoke(new MethodInvoker(delegate ()
            {
                //uiBtn_Parse.Enabled = true;
            }));
        }
 
        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)
            {
                //리스트에 학생들의 정보 저장
                AddStuList(xmlDs);
 
                //DataView Binding
                uiDGV_Main.DataSource = GetDataTable(xmlDs);
            }
        }
 
        /// <summary>
        /// 파싱된 XML 데이터 DB 테이블에 저장시키기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiBtn_Insert_Click(object sender, EventArgs e)
        {
            string name = string.Empty;
            string age = string.Empty;
            string grade = string.Empty;
            string major = string.Empty;
 
            string query = string.Empty;
 
            for (int idx = 0; idx < stuList.Count; idx++)
            {
                name = stuList[idx].Name.ToString();
                age = stuList[idx].Age.ToString();
                grade = stuList[idx].Grade.ToString();
                major = stuList[idx].Major.ToString();
 
                query = @"
            INSERT INTO dbo.STUDENT 
            VALUES ('#NAME', '#AGE', '#GRADE', '#PHONENUMBER')
            ";
 
                query = query.Replace("#NAME", name);
                query = query.Replace("#AGE", age);
                query = query.Replace("#GRADE", grade);
                query = query.Replace("#PHONENUMBER", major);
 
                int result = MssqlManager.Instance.ExecuteNonQuery(query);
 
                if (result < 0)
                {
                    MessageBox.Show("DB Insert 실패");
                }
            }
 
            MessageBox.Show("데이터베이스 Insert 성공");
        }
 
        /// <summary>
        /// DataTable 생성
        /// </summary>
        /// <returns></returns>
        private DataTable GetDataTable(DataSet ds)
        {
            return ds.Tables[0];
        }
 
        /// <summary>
        /// XML 데이터 List에 저장
        /// </summary>
        private void AddStuList(DataSet ds)
        {
            for(int row = 0; row < ds.Tables[0].Rows.Count; row++)
            {
                Student stu = new Student(); //student 객체 생성
                stu.Name = ds.Tables[0].Rows[row]["STD_NAME"].ToString();
                stu.Age = Convert.ToInt32(ds.Tables[0].Rows[row]["STD_AGE"].ToString());
                stu.Grade = ds.Tables[0].Rows[row]["STD_GRADE"].ToString();
                stu.Major = ds.Tables[0].Rows[row]["STD_MAJOR"].ToString();
 
                stuList.Add(stu);
            }
        }
 
        /// <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의 데이터를 잘 읽어서 파싱을 하고, Insert 버튼을 클릭하면 DB Student 테이블에 알맞게 Insert되어 저장된 모습을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY