C# 윈폼 DataGridView 데이터 조회, 추가, 삭제하는 방법


 

이번 포스팅에서는 실무에서도 많이 사용하는 DataGridView 컨트롤 사용방법과 또한, 데이터베이스와 연동하여 해당 데이터를 조회하여 UI에서 바인딩 하는 방법과 데이터 추가(Add), 삭제(Delete), 수정(Update) 하는 방법에 대해서 알려드리도록 하겠습니다.

 

부가적으로 DataGridView 컨트롤 디자인 하는 코드도 들어 있음으로써, 향후에 디자인이 필요하신 분은 참고하시면 되겠습니다.

 

저의 작업 환경은 VisualStudio 2015를 이용하여 프로그램을 만들었고, DatabaseOracle 11g를 사용하였습니다.


간단히 Database에서 Student라는 Table을 하나 만들어 주고, 이제 해당 Student Table을 윈폼 DataGridView 컨트롤을 이용하여 Database와 연동하여 해당 데이터를 조회, 추가, 삭제, 수정 하는 방법을 차례대로 소스와 함께 보여드리도록 하겠습니다.


 

그러면 아래와 같이 빈 윈도우 폼을 생성해 주시고,
DataGridView
컨트롤을 배치하여 주시기 바랍니다.



▲ 위와 같이 보시게 되면 STUDENT라는 Lable 컨트롤을 배치 하였고,

 


추가, 수정, 삭제 총 3개의 Button 컨트롤을 배치하여 각각 btn_add, btn_update, btn_delete 라는 컨트롤 Name을 지정하여 Click 이벤트를 만들어 주었습니다.



마지막으로 DataGridView 컨트롤을 중앙부에 배치하였고, 컨트롤 Name 을 datagridview1로 설정하였습니다.




그리고 Database에서는 STUDENT 테이블을 하나 생성해 주시고 테스트 데이터를 사용자 마음대로 Insert 해주시기 바랍니다. 저는 아래와 같이 Table을 생성하였습니다.




 

여기까지 하셨다면, 이제 데이터를 조회하고, 추가, 삭제, 수정 하는 방법을 아래 코드로 보여드리겠습니다.


참고로, 오라클 연동하는 코드는 이전에 게시글로 올렸기 때문에 따로 코드를 올리지는 않겠습니다~~


오라클 연동하는 소스코드는 아래 블로그 링크로 가시게 되면 소스코드를 보실 수 있습니다.^^


오라클 연동 : http://afsdzvcx123.tistory.com/127


 

[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

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace Test

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            this.Load += Main_Load;

        }

 

        private void Main_Load(object sender, EventArgs e)

        {

            try

            {

                Student_Data_View_Load();

                Student_Data_View_Design();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString(), "Error",

                MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

 

        private static void ConnectToDB()

        {

 

            while (OracleDBManager.Instance.GetConnection() == false)

            {

                MessageBox.Show("Database Connected Fail...");

 

                return;

            }

 

            MessageBox.Show("Database Connected Success!!");

        }

 

        /// <summary>

        /// STUDENT 테이블에서 데이터 조회하여

        /// DataGridView 데이터 보여줌

        /// </summary>

        private void Student_Data_View_Load()

        {

            try

            {

                string query = @"SELECT * FROM STUDENT";

 

                DataSet ds = new System.Data.DataSet();

                OracleDBManager.Instance.ExecuteDsQuery(ds, query);

 

                if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)

                    return;

 

                dataGridView1.DataSource = ds.Tables[0];

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString(), "Error",

                MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

 

        /// <summary>

        /// Student 테이블에 데이터 추가

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btn_add_Click(object sender, EventArgs e)

        {

            try

            {

                this.Cursor = Cursors.WaitCursor;

 

                DataTable dtChanges = new DataTable();

                DataTable dtProcessFlag = (DataTable)dataGridView1.DataSource;

 

                dtChanges = dtProcessFlag.GetChanges(DataRowState.Added);

 

                string insert_query = string.Empty;

 

                if (dtChanges != null)

                {

                    for (int i = 0; i < dtChanges.Rows.Count; i++)

                    {

                        insert_query = @"INSERT INTO STUDENT (NAME, AGE, GRADE)" +

 

                        string.Format("VALUES ('{0}', '{1}', '{2}')",

                        dtChanges.Rows[i]["NAME"].ToString(),

                        dtChanges.Rows[i]["AGE"].ToString(),

                        dtChanges.Rows[i]["GRADE"].ToString());

 

                        int result = OracleDBManager.Instance.ExecuteNonQuery(insert_query);

 

                        if (result < 0return;

                    }

                }

                dtChanges = null;

 

                Student_Data_View_Load();

 

                this.Cursor = Cursors.Default;

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString(), "Error",

            MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

 

            MessageBox.Show("Database Data Insert Success",

        "Data Insert Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

 

        /// <summary>

        /// Student 테이블에 데이터 수정

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btn_update_Click(object sender, EventArgs e)

        {

            try

            {

                this.Cursor = Cursors.WaitCursor;

 

                DataTable dtChanges = new DataTable();

                DataTable dtProcessFlag = (DataTable)dataGridView1.DataSource;

 

                dtChanges = dtProcessFlag.GetChanges(DataRowState.Modified);

 

                string update_query = string.Empty;

 

                if (dtChanges != null)

                {

                    for (int i = 0; i < dtChanges.Rows.Count; i++)

                    {

 

                        update_query = @"UPDATE STUDENT SET NAME = '#NAME'

                                         WHERE GRADE = '#GRADE'";

                        update_query = update_query.Replace("#NAME", dtChanges.Rows[i]["NAME"].ToString());

                        update_query = update_query.Replace("#GRADE", dtChanges.Rows[i]["GRADE"].ToString());

 

                        int result = OracleDBManager.Instance.ExecuteNonQuery(update_query);

 

                        if (result < 0return;

                    }

                }

                dtChanges = null;

 

                Student_Data_View_Load();

 

                this.Cursor = Cursors.Default;

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

 

            MessageBox.Show("Database Data Update Success",

           "Data Update Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

 

        /// <summary>

        /// Student 테이블에 데이터 삭제

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btn_delete_Click(object sender, EventArgs e)

        {

            try

            {

                this.Cursor = Cursors.WaitCursor;

 

                if (dataGridView1.SelectedRows.Count == 0)

                {

                    return;

                }

 

                string selected_Process_Name = dataGridView1.CurrentRow.Cells["NAME"].Value.ToString();

 

                string delete_query = @"DELETE FROM STUDENT WHERE NAME = '#NAME'";

 

                delete_query = delete_query.Replace("#NAME", selected_Process_Name);

 

                int result = OracleDBManager.Instance.ExecuteNonQuery(delete_query);

 

                if (result < 0return;

 

                Student_Data_View_Load();

 

                this.Cursor = Cursors.Default;

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

 

            MessageBox.Show("Database Data Delete Success""Data Delete Success"

          MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

 

        /// <summary>

        /// DataGridView 사이즈 조절

        /// </summary>

        private void Student_Data_View_Design()

        {

            try

            {

                dataGridView1.AutoGenerateColumns = true;

                //DataGridView 사이즈에 맞게 자동 조정

                dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

 

                this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;

 

 

                //DataGridView 일반 Row 디자인

                dataGridView1.BorderStyle = BorderStyle.None;

                dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(238239249);

                dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.Single;

                dataGridView1.DefaultCellStyle.Font = new Font("굴림"11, FontStyle.Bold);

                //Row 오른쪽 정렬

                dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; 

                                                                                                     

                dataGridView1.DefaultCellStyle.SelectionBackColor = Color.LightSkyBlue;

                dataGridView1.DefaultCellStyle.SelectionForeColor = Color.WhiteSmoke;

                dataGridView1.BackgroundColor = Color.White;

 

                //DataGridView ColumnHeader 디자인

                dataGridView1.EnableHeadersVisualStyles = false;

                dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;

                dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("굴림"11, FontStyle.Bold);

                //dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(15, 50, 72);

                dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(155072);

                //Header Colunm 오른쪽 정렬

                dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; 

                dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White; //컬럼명 폰트 컬러

 

                //DataGridView RowHeader 디자인

                //dataGridView.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(15, 50, 72);

                dataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(155072);

                dataGridView1.RowHeadersDefaultCellStyle.Font = new Font("굴림"11, FontStyle.Bold);

                dataGridView1.RowHeadersDefaultCellStyle.ForeColor = Color.White;// 로우명 폰트 컬러

                dataGridView1.RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

    }

}

 

Colored by Color Scripter

cs

 

간단히 위의 소스코드를 설명 드리자면, 총 7개의 메서드가 있는 것을 보실 수 있습니다.

제가 각각 메서드가 하는 역할에 대해서는 주석을 달아 놓았지만 다시 정리를 하자면

1. private void Main_Load(object sender, EventArgs e) - 폼이 Load 되면, DB 내용 조회하여 DataGridView에 데이터 보여주는 Load 이벤트 핸들러 

2. private static void ConnectToDB() - Database 접속 유무 체크 하는 메서드

3. private void Student_Data_View_Load() - STUDENT 테이블에서 데이터 조회하여 DataGridView에 데이터 보여주는 메서드

4. private void btn_add_Click(object sender, EventArgs e) - Student 테이블에 데이터 추가 하는 클릭 이벤트

5. private void btn_update_Click(object sender, EventArgs e) - Student 테이블에 데이터 수정 하는 클릭 이벤트 

6. private void btn_delete_Click(object sender, EventArgs e) -  Student 테이블에 데이터 삭제 하는 클릭 이벤트

7. private void Student_Data_View_Design() - DataGridView 디자인 및 사이즈 조절하는 메서드


여기까지 따라하셨다면, 이제 프로그램이 제대로 동작 하는지 빌드를 해주시고 제대로 작동이 된다면 아래와 같은 실행 결과를 보실 수 있습니다ㅎㅎ

[실행결과 화면]

[데이터 조회]


보시다시피, 해당 STUDENT 테이블에서 데이터를 알맞게 조회하여 DataGridView에 데이터를 보여주는 것을 볼 수 있습니다.


 

[데이터 추가]



위와 같이 학생 범범조조가 추가되었고, Database에도 바로 반영된 것을 확인 하실 수 있습니다.


 

[데이터 수정]



위와 같이 유광영이라는 학생 Name원숭이로 수정하였고, 바로 DatabaseUpdate 된 것을 확인하실 수 있습니다.


 

[데이터 삭제]

위와 같이 유야인학생을 삭제하였더니, DataGridView에서도 삭제가 되었고, Database에서도 삭제된 모습을 확인 하실 수 있습니다.

 

부족한 글 읽어주셔서 감사합니다.^^

 

다음에 DataGridView 사용에 있어서 더 좋은 기술과 좋은 디자인을 알게 된다면 또 자료를 올리도록 하겠습니다.


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY