반응형

DataGridView에 출력한 내용을 수정하고 XML로 저장해 보자.

 

WinForm에 DataGridView, Button을 적당히 배치한다.

 

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        DataTable dataTable;
        string selectedCellString;
 
        public Form1()
        {
            InitializeComponent();
 
            try
            {
                dataTable = new DataTable("game");
                dataTable.ReadXmlSchema("gamelist.xml");
                dataTable.ReadXml("gamelist.xml");
                dataGridView1.DataSource = dataTable;
 
                // 데이터 테이블 내용 변경 후 콜백함수 지정.
                dataTable.RowChanged += DataTable_RowChanged;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void DataTable_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            // 변경된 내용 표시
            MessageBox.Show(selectedCellString + " => " +
                e.Row[dataGridView1.SelectedCells[0].ColumnIndex].ToString(), "변경");
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            // 저장
            dataTable.WriteXml("gamelist.xml");
        }
 
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            // 프로그램 시작 시 인덱스 에러 방지
            if (dataGridView1.SelectedCells.Count < 1)
                return;
 
            selectedCellString = dataGridView1.SelectedCells[0].Value.ToString();
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

실행하면 'gamelist.xml' 의 내용이 표시된다.

 

원하는 셀을 수정하고 저장 버튼을 클릭한다.

 

 

원본 'gamelist.xml'

 

수정된 'gamelist.xml'

DataGridView에서 수정한 내용과 함께 <gameList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 태그도 <DocumentElement>로 변경되었다.

 

반응형
Posted by J-sean
:
반응형

DataTable 이나 DataSet 클래스를 이용해 XML 파일을 생성하고 읽어올 수 있다. 이 두 클래스로 생성한 XML 파일이 아닌 임의의 XML 파일을 읽어서 DataGridView에 표시해 보자.

 

WinForm에 DataGridView를 적당히 배치한다.

 

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            try
            {
                DataTable dataTable = new DataTable("game");
                dataTable.ReadXmlSchema("gamelist.xml");
                // 'gamelist.xml'은 인터넷에서 주워온 파일이다.
                // DataTable.WriteXml()에 XmlWriteMode.WriteSchema
                // 옵션을 줘서 만든 XML 파일이 아니면 DataTable 클래스
                // 생성시 테이블 이름("game")을 정확히 지정해 주고
                // Schema를 읽어와야 한다.                
                dataTable.ReadXml("gamelist.xml");
                dataGridView1.DataSource = dataTable;
 
                /* DataSet 클래스 사용 예. 더 간단하다.
                DataSet dataSet = new DataSet();
                dataSet.ReadXml("gamelist.xml");
                dataGridView1.DataSource = dataSet.Tables["game"];
                //dataGridView1.DataSource = dataSet.Tables[0];
                */
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

'gamelist.xml' 파일의 구성

 

gamelist.xml
5.73MB

 

실행하면 gamelist.xml의 내용이 표시된다.

 

반응형
Posted by J-sean
:
반응형

C# WinForm과 SQLite를 이용해 간단한 회원관리 프로그램을 만들어 보자.

 

DataGridView, Button등을 윈폼에 적당히 배치한다.

 

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using System.Data.SQLite;
 
namespace Manager
{
    public partial class Form1 : Form
    {
        SQLiteConnection connection;
        SQLiteCommand command;
        DataTable dataTable;
 
        public Form1()
        {
            InitializeComponent();
 
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.ReadOnly = true;
            dataGridView1.AllowUserToAddRows = false;
 
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox1.Items.Add("아이디로");
            comboBox1.Items.Add("이름으로");
            comboBox1.Items.Add("생일로");
            comboBox1.SelectedIndex = 0;
 
            try
            {
                connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                connection.Open();
 
                command = new SQLiteCommand(connection);
                command.CommandText = "CREATE TABLE IF NOT EXISTS member (" +
                    "id TEXT UNIQUE NOT NULL, " +
                    "name TEXT NOT NULL, " +
                    "birthday TEXT NOT NULL)";
                command.ExecuteNonQuery();
 
                command.CommandText = "SELECT * FROM member";
                SQLiteDataReader reader = command.ExecuteReader();
                dataTable = new DataTable();
                dataTable.Load(reader);
                dataGridView1.DataSource = dataTable;
                reader.Close();
 
                dataGridView1.Columns[0].HeaderText = "아이디";
                dataGridView1.Columns[1].HeaderText = "이름";
                dataGridView1.Columns[2].HeaderText = "생일";
 
                connection.Close();
 
                label4.Text = "총 회원수: " + dataGridView1.Rows.Count;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try // 회원 정보 수정
            {
                foreach (DataGridViewRow row in dataGridView1.Rows) // 아이디(변경불가 상황 가정)를 바꾸려 시도하는 경우 체크
                {
                    if (row.Cells[0].Value.ToString() == textBox1.Text.Trim()) // 아이디 비교
                    {
                        if (MessageBox.Show(row.Cells[1].Value + "의 데이터를 수정 합니다. 수정하시겠습니까?",
                            "수정", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                            connection.Open();
 
                            command = new SQLiteCommand(connection);
                            command.CommandText = "UPDATE member set name=:name, birthday=:birthday WHERE id=:id";
                            command.Parameters.Add("name", DbType.String).Value = textBox2.Text.Trim();
                            command.Parameters.Add("birthday", DbType.String).Value = textBox3.Text.Trim();
                            command.Parameters.Add("id", DbType.String).Value = textBox1.Text.Trim();
                            command.ExecuteNonQuery();
 
                            connection.Close();
 
                            row.Cells[0].Value = textBox1.Text.Trim();
                            row.Cells[1].Value = textBox2.Text.Trim();
                            row.Cells[2].Value = textBox3.Text.Trim();
 
                            return;
                        }
                        else
                        {
                            //MessageBox.Show("바뀌지 않았습니다.");
                            return;
                        }
                    }
                }
                MessageBox.Show(textBox1.Text + "는 존재하지 않는 ID 입니다.");
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            // 프로그램 시작 시 인덱스 에러 방지
            if (dataGridView1.SelectedRows.Count < 1)
                return;
 
            DataGridViewRow row = dataGridView1.SelectedRows[0];
            textBox1.Text = row.Cells[0].Value.ToString();
            textBox2.Text = row.Cells[1].Value.ToString();
            textBox3.Text = row.Cells[2].Value.ToString();
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            try // 회원 추가
            {
                connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                connection.Open();
 
                command = new SQLiteCommand(connection);
                command.CommandText = $"INSERT INTO member (id, name, birthday) VALUES (" +
                    $"'{textBox1.Text.Trim()}', '{textBox2.Text.Trim()}', '{textBox3.Text.Trim()}')";
                command.ExecuteNonQuery();
 
                connection.Close();
 
                dataTable.Rows.Add(textBox1.Text.Trim(), textBox2.Text.Trim(), textBox3.Text.Trim());
                label4.Text = "총 회원수: " + dataGridView1.Rows.Count;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            try // 회원 삭제
            {
                if (MessageBox.Show($"{dataGridView1.SelectedRows[0].Cells[1].Value}의 데이터를 정말 삭제 하시겠습니까?",
                    "삭제", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                    connection.Open();
 
                    command = new SQLiteCommand(connection);
                    command.CommandText = "DELETE from member WHERE id=:id";
                    command.Parameters.Add("id", DbType.String).Value = textBox1.Text.Trim();
                    command.ExecuteNonQuery();
 
                    connection.Close();
 
                    DataGridViewRow row = dataGridView1.SelectedRows[0];
                    dataGridView1.Rows.Remove(row);
 
                    label4.Text = "총 회원수: " + dataGridView1.Rows.Count;
                }
                else
                {
                    //MessageBox.Show("삭제하지 않았습니다");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void button4_Click(object sender, EventArgs e)
        {
            try // 검색
            {
                string filter;
                switch (comboBox1.SelectedIndex)
                {
                    case 0:
                        filter = "id";
                        break;
 
                    case 1:
                        filter = "name";
                        break;
 
                    case 2:
                        filter = "birthday";
                        break;
 
                    default:
                        filter = "id";
                        break;
                }
 
                connection = new SQLiteConnection("Data Source=" + Application.StartupPath + "/member.db");
                connection.Open();
                command = new SQLiteCommand(connection);
 
                if (textBox4.Text.Trim().Length == 0)
                {
                    command.CommandText = $"SELECT * FROM member";
                }
                else
                {
                    command.CommandText = $"SELECT * FROM member where {filter}='{textBox4.Text.Trim()}'";
                }
                SQLiteDataReader reader = command.ExecuteReader();
                dataTable = new DataTable();
                dataTable.Load(reader);
                dataGridView1.DataSource = dataTable;
                reader.Close();
 
                connection.Close();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            // 항목 번호 그리기
            String rowIndex = (e.RowIndex + 1).ToString();
 
            StringFormat centerFormat = new StringFormat()
            {
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };
 
            Rectangle headerBound = new Rectangle(e.RowBounds.Left, e.RowBounds.Top,
                dataGridView1.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowIndex, Font, SystemBrushes.ControlText, headerBound, centerFormat);
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

프로그램을 실행하면 빈 데이터베이스가 생성된다.

 

회원 추가, 수정, 삭제, 검색등을 해 본다.

 

반응형
Posted by J-sean
: