연습: 바인딩되지 않은 Windows Forms DataGridView 컨트롤 만들기
데이터베이스에서 시작되지 않은 테이블 형식 데이터를 자주 표시하려고 할 수 있습니다. 예를 들어, 2차원 문자열 배열의 콘텐츠를 표시하려고 할 수 있습니다. DataGridView 클래스는 데이터 원본에 바인딩하지 않고 데이터를 표시하는 쉽고 고도로 사용자 지정 가능한 방법을 제공합니다. 이 연습에서는 DataGridView 컨트롤을 채우고 “바인딩 안 됨” 모드에서 행의 추가 및 삭제를 관리하는 방법을 보여 줍니다. 기본적으로 사용자는 새 행을 추가할 수 있습니다. 행 추가를 방지하려면 AllowUserToAddRows 속성을 false
로 설정합니다.
이 항목의 코드를 단일 목록으로 복사하려면 방법: 방법: 바인딩되지 않은 Windows Forms DataGridView 컨트롤 만들기를 참조하세요.
폼 만들기
바인딩되지 않은 DataGridView 컨트롤을 사용하려면
Form에서 파생되고 다음 변수 선언과
Main
메서드를 포함하는 클래스를 만듭니다.using System; using System.Drawing; using System.Windows.Forms; public class Form1 : System.Windows.Forms.Form { private Panel buttonPanel = new Panel(); private DataGridView songsDataGridView = new DataGridView(); private Button addNewRowButton = new Button(); private Button deleteRowButton = new Button();
Imports System.Drawing Imports System.Windows.Forms Public Class Form1 Inherits System.Windows.Forms.Form Private buttonPanel As New Panel Private WithEvents songsDataGridView As New DataGridView Private WithEvents addNewRowButton As New Button Private WithEvents deleteRowButton As New Button
[STAThreadAttribute()] static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); } }
<STAThreadAttribute()> _ Public Shared Sub Main() Application.EnableVisualStyles() Application.Run(New Form1()) End Sub End Class
양식의 클래스 정의에
SetupLayout
메서드를 구현하여 양식 레이아웃을 설정합니다.private void SetupLayout() { this.Size = new Size(600, 500); addNewRowButton.Text = "Add Row"; addNewRowButton.Location = new Point(10, 10); addNewRowButton.Click += new EventHandler(addNewRowButton_Click); deleteRowButton.Text = "Delete Row"; deleteRowButton.Location = new Point(100, 10); deleteRowButton.Click += new EventHandler(deleteRowButton_Click); buttonPanel.Controls.Add(addNewRowButton); buttonPanel.Controls.Add(deleteRowButton); buttonPanel.Height = 50; buttonPanel.Dock = DockStyle.Bottom; this.Controls.Add(this.buttonPanel); }
Private Sub SetupLayout() Me.Size = New Size(600, 500) With addNewRowButton .Text = "Add Row" .Location = New Point(10, 10) End With With deleteRowButton .Text = "Delete Row" .Location = New Point(100, 10) End With With buttonPanel .Controls.Add(addNewRowButton) .Controls.Add(deleteRowButton) .Height = 50 .Dock = DockStyle.Bottom End With Me.Controls.Add(Me.buttonPanel) End Sub
SetupDataGridView
메서드를 만들어 DataGridView 열 및 속성을 설정합니다.이 메서드는 먼저 DataGridView 컨트롤을 양식의 Controls 컬렉션에 추가합니다. 다음으로, ColumnCount 속성을 사용하여 표시할 열의 수를 설정합니다. 열 머리글의 기본 스타일은 ColumnHeadersDefaultCellStyle 속성에서 반환된 DataGridViewCellStyle 의 BackColor, ForeColor 및 Font 속성을 설정하여 지정됩니다.
레이아웃 및 모양 속성이 설정된 다음, 열 이름이 할당됩니다. 이 메서드가 종료되면 DataGridView 컨트롤을 채울 준비가 됩니다.
private void SetupDataGridView() { this.Controls.Add(songsDataGridView); songsDataGridView.ColumnCount = 5; songsDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy; songsDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White; songsDataGridView.ColumnHeadersDefaultCellStyle.Font = new Font(songsDataGridView.Font, FontStyle.Bold); songsDataGridView.Name = "songsDataGridView"; songsDataGridView.Location = new Point(8, 8); songsDataGridView.Size = new Size(500, 250); songsDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders; songsDataGridView.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single; songsDataGridView.CellBorderStyle = DataGridViewCellBorderStyle.Single; songsDataGridView.GridColor = Color.Black; songsDataGridView.RowHeadersVisible = false; songsDataGridView.Columns[0].Name = "Release Date"; songsDataGridView.Columns[1].Name = "Track"; songsDataGridView.Columns[2].Name = "Title"; songsDataGridView.Columns[3].Name = "Artist"; songsDataGridView.Columns[4].Name = "Album"; songsDataGridView.Columns[4].DefaultCellStyle.Font = new Font(songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic); songsDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; songsDataGridView.MultiSelect = false; songsDataGridView.Dock = DockStyle.Fill; songsDataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler( songsDataGridView_CellFormatting); }
Private Sub SetupDataGridView() Me.Controls.Add(songsDataGridView) songsDataGridView.ColumnCount = 5 With songsDataGridView.ColumnHeadersDefaultCellStyle .BackColor = Color.Navy .ForeColor = Color.White .Font = New Font(songsDataGridView.Font, FontStyle.Bold) End With With songsDataGridView .Name = "songsDataGridView" .Location = New Point(8, 8) .Size = New Size(500, 250) .AutoSizeRowsMode = _ DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders .ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single .CellBorderStyle = DataGridViewCellBorderStyle.Single .GridColor = Color.Black .RowHeadersVisible = False .Columns(0).Name = "Release Date" .Columns(1).Name = "Track" .Columns(2).Name = "Title" .Columns(3).Name = "Artist" .Columns(4).Name = "Album" .Columns(4).DefaultCellStyle.Font = _ New Font(Me.songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic) .SelectionMode = DataGridViewSelectionMode.FullRowSelect .MultiSelect = False .Dock = DockStyle.Fill End With End Sub
PopulateDataGridView
메서드를 만들어 DataGridView 컨트롤에 행을 추가합니다.각 행은 노래 및 관련 정보를 나타냅니다.
private void PopulateDataGridView() { 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" }; songsDataGridView.Rows.Add(row0); songsDataGridView.Rows.Add(row1); songsDataGridView.Rows.Add(row2); songsDataGridView.Rows.Add(row3); songsDataGridView.Rows.Add(row4); songsDataGridView.Rows.Add(row5); songsDataGridView.Rows.Add(row6); songsDataGridView.Columns[0].DisplayIndex = 3; songsDataGridView.Columns[1].DisplayIndex = 4; songsDataGridView.Columns[2].DisplayIndex = 0; songsDataGridView.Columns[3].DisplayIndex = 1; songsDataGridView.Columns[4].DisplayIndex = 2; }
Private Sub PopulateDataGridView() Dim row0 As String() = {"11/22/1968", "29", "Revolution 9", _ "Beatles", "The Beatles [White Album]"} Dim row1 As String() = {"1960", "6", "Fools Rush In", _ "Frank Sinatra", "Nice 'N' Easy"} Dim row2 As String() = {"11/11/1971", "1", "One of These Days", _ "Pink Floyd", "Meddle"} Dim row3 As String() = {"1988", "7", "Where Is My Mind?", _ "Pixies", "Surfer Rosa"} Dim row4 As String() = {"5/1981", "9", "Can't Find My Mind", _ "Cramps", "Psychedelic Jungle"} Dim row5 As String() = {"6/10/2003", "13", _ "Scatterbrain. (As Dead As Leaves.)", _ "Radiohead", "Hail to the Thief"} Dim row6 As String() = {"6/30/1992", "3", "Dress", "P J Harvey", "Dry"} With Me.songsDataGridView.Rows .Add(row0) .Add(row1) .Add(row2) .Add(row3) .Add(row4) .Add(row5) .Add(row6) End With With Me.songsDataGridView .Columns(0).DisplayIndex = 3 .Columns(1).DisplayIndex = 4 .Columns(2).DisplayIndex = 0 .Columns(3).DisplayIndex = 1 .Columns(4).DisplayIndex = 2 End With End Sub
유틸리티 메서드를 사용하여 이벤트 처리기를 연결할 수 있습니다.
추가 및 삭제 단추의 Click 이벤트, 양식의 Load 이벤트, DataGridView 컨트롤의 CellFormatting 이벤트를 처리합니다.
추가 단추의 Click 이벤트가 발생하면 새로운 빈 행이 DataGridView에 추가됩니다.
삭제 단추의 Click 이벤트가 발생하는 경우 선택한 행이 사용자가 새 행을 추가할 수 있는 새 레코드의 행이 아니면 해당 행이 삭제됩니다. 이 행은 항상 DataGridView 컨트롤의 마지막 행입니다.
양식의 Load 이벤트가 발생하면
SetupLayout
,SetupDataGridView
및PopulateDataGridView
유틸리티 메서드가 호출됩니다.CellFormatting 이벤트가 발생하는 경우 셀 값을 구문 분석할 수 있으면
Date
열의 각 셀은 긴 날짜 형식으로 지정됩니다.public Form1() { this.Load += new EventHandler(Form1_Load); } private void Form1_Load(System.Object sender, System.EventArgs e) { SetupLayout(); SetupDataGridView(); PopulateDataGridView(); } private void songsDataGridView_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e) { if (e != null) { if (this.songsDataGridView.Columns[e.ColumnIndex].Name == "Release Date") { if (e.Value != null) { try { e.Value = DateTime.Parse(e.Value.ToString()) .ToLongDateString(); e.FormattingApplied = true; } catch (FormatException) { Console.WriteLine("{0} is not a valid date.", e.Value.ToString()); } } } } } private void addNewRowButton_Click(object sender, EventArgs e) { this.songsDataGridView.Rows.Add(); } private void deleteRowButton_Click(object sender, EventArgs e) { if (this.songsDataGridView.SelectedRows.Count > 0 && this.songsDataGridView.SelectedRows[0].Index != this.songsDataGridView.Rows.Count - 1) { this.songsDataGridView.Rows.RemoveAt( this.songsDataGridView.SelectedRows[0].Index); } }
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load SetupLayout() SetupDataGridView() PopulateDataGridView() End Sub Private Sub songsDataGridView_CellFormatting(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _ Handles songsDataGridView.CellFormatting If e IsNot Nothing Then If Me.songsDataGridView.Columns(e.ColumnIndex).Name = _ "Release Date" Then If e.Value IsNot Nothing Then Try e.Value = DateTime.Parse(e.Value.ToString()) _ .ToLongDateString() e.FormattingApplied = True Catch ex As FormatException Console.WriteLine("{0} is not a valid date.", e.Value.ToString()) End Try End If End If End If End Sub Private Sub addNewRowButton_Click(ByVal sender As Object, _ ByVal e As EventArgs) Handles addNewRowButton.Click Me.songsDataGridView.Rows.Add() End Sub Private Sub deleteRowButton_Click(ByVal sender As Object, _ ByVal e As EventArgs) Handles deleteRowButton.Click If Me.songsDataGridView.SelectedRows.Count > 0 AndAlso _ Not Me.songsDataGridView.SelectedRows(0).Index = _ Me.songsDataGridView.Rows.Count - 1 Then Me.songsDataGridView.Rows.RemoveAt( _ Me.songsDataGridView.SelectedRows(0).Index) End If End Sub
애플리케이션 테스트
이제 양식을 테스트하여 예상대로 동작하는지 확인할 수 있습니다.
양식을 테스트하려면
F5 키를 눌러 애플리케이션을 실행합니다.
PopulateDataGridView
에 나열된 노래를 표시하는 DataGridView 컨트롤이 표시됩니다. 행 추가 단추를 사용하여 새 행을 추가할 수 있으며 행 삭제 단추를 사용하여 선택한 행을 삭제할 수 있습니다. 바인딩되지 않은 DataGridView 컨트롤은 데이터 저장소이며 해당 데이터는 DataSet 또는 배열 등의 외부 원본과 관련이 없습니다.
다음 단계
이 애플리케이션은 DataGridView 컨트롤의 기능에 대한 기본적인 이해를 제공합니다. 다음과 같은 여러 가지 방법으로 DataGridView 컨트롤의 모양과 동작을 사용자 지정할 수 있습니다.
테두리 및 헤더 스타일을 변경합니다. 자세한 내용은 방법: 테두리 및 Windows Forms DataGridView 컨트롤의 모눈선 스타일 변경합니다.
DataGridView 컨트롤에 대한 사용자 입력을 사용 설정 또는 제한합니다. 자세한 내용은 방법: Windows Forms DataGridView 컨트롤에서 행 추가 및 삭제 금지 및 방법: Windows Forms DataGridView 컨트롤에서 열을 읽기 전용으로 설정을 참조하세요.
데이터베이스 관련 오류에 대한 사용자 입력을 확인합니다. 자세한 내용은 연습: Windows Forms DataGridView 컨트롤에서 데이터 입력 중에 발생하는 오류 처리를 참조하세요.
가상 모드를 사용하여 매우 큰 데이터 집합을 처리합니다. 자세한 내용은 연습: Windows Forms DataGridView 컨트롤에서 가상 모드 구현을 참조하세요.
셀의 모양을 사용자 지정합니다. 자세한 내용은 방법: Windows Forms DataGridView 컨트롤에서 셀 모양 사용자 지정 및 방법: Windows Forms DataGridView 컨트롤에 기본 셀 스타일 설정을 참조하세요.
참고 항목
.NET Desktop feedback
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기