티스토리 뷰

[C#] DataGridView컨트롤에 데이터를 삽입하는 예제 소스

오늘은 C#에서 DataGridView컨트롤에 데이터를 삽입하는 예제를 해보도록 하겠습니다.

아래와 같이 순서대로 하시면 됩니다^^


[1단계] 프로젝트를 생성하고 폼에 DataGridView를 추가합니다.


위와 같이 폼에 꽉차게 DataGridView를 그려줍니다.

DataGridView의 이름은 기본적으로 dataGridView1로 생성되는데요. 그대로 사용하도록 하겠습니다.



[2단계] 소스에 다음을 추가합니다.

        /*
         * SetupDataGridView()
         * DataGridView의 기본적인 설정을 합니다.
         */
        private void SetupDataGridView()
        {
            this.Controls.Add(dataGridView1);

            // DataGridView의 컬럼 갯수를 5개로 설정합니다.
            dataGridView1.ColumnCount = 5;

            // DataGridView에 컬럼을 추가합니다.
            dataGridView1.Columns[0].Name = "Release Date";
            dataGridView1.Columns[1].Name = "Track";
            dataGridView1.Columns[2].Name = "Title";
            dataGridView1.Columns[3].Name = "Artist";
            dataGridView1.Columns[4].Name = "Album";
        }
        
        /*
         * PopulateDataGridView()
         * DataGridView에 데이터를 삽입합니다.
         */
        private void PopulateDataGridView()
        {
            // DataGridView에 삽입할 데이터를 설정합니다.
            string[] row0 = { "11/22/1968", "29", "Revolution 9", "Beatles", "The Beatles [White Album]" };
            string[] row1 = { "1960", "6", "Fools Rush In", "Frank Sinatra", "Nice 'N' Easy" };
            string[] row2 = { "11/11/1971", "1", "One of These Days", "Pink Floyd", "Meddle" };
            string[] row3 = { "1988", "7", "Where Is My Mind?", "Pixies", "Surfer Rosa" };
            string[] row4 = { "5/1981", "9", "Can't Find My Mind", "Cramps", "Psychedelic Jungle" };
            string[] row5 = { "6/10/2003", "13", "Scatterbrain. (As Dead As Leaves.)", "Radiohead", "Hail to the Thief" };
            string[] row6 = { "6/30/1992", "3", "Dress", "P J Harvey", "Dry" };

            // DataGridView에 한 줄씩 삽입합니다.
            dataGridView1.Rows.Add(row0);
            dataGridView1.Rows.Add(row1);
            dataGridView1.Rows.Add(row2);
            dataGridView1.Rows.Add(row3);
            dataGridView1.Rows.Add(row4);
            dataGridView1.Rows.Add(row5);
            dataGridView1.Rows.Add(row6);

            // DataGridView에 들어갈 컬럼의 순서를 지정합니다.
            dataGridView1.Columns[0].DisplayIndex = 3;
            dataGridView1.Columns[1].DisplayIndex = 4;
            dataGridView1.Columns[2].DisplayIndex = 0;
            dataGridView1.Columns[3].DisplayIndex = 1;
            dataGridView1.Columns[4].DisplayIndex = 2;
        }

 



[3단계] 폼이 로드될 때 실행될 동작을 지정합니다.

         private void Form1_Load(object sender, EventArgs e)
        {
            SetupDataGridView();
            PopulateDataGridView();
        }


그리고 실행하시면 아래와 같이 나옵니다.^^


소스를 압축해서 첨부합니다.^^

ex_dataGridView2.zip

댓글