연습: Windows Forms DataGridView 컨트롤에서 데이터 유효성 검사
사용자에게 데이터 입력 기능을 표시할 때 양식에 입력한 데이터의 유효성을 검사해야 하는 경우가 자주 있습니다. DataGridView 클래스는 데이터가 데이터 저장소에 커밋되기 전에 유효성 검사를 수행하는 편리한 방법을 제공합니다. 현재 셀이 변경될 때 DataGridView에 의해 발생하는 CellValidating 이벤트를 처리하여 데이터의 유효성을 검사할 수 있습니다.
이 연습에서는 Northwind 샘플 데이터베이스의 Customers
표에서 행을 검색하고 이를 DataGridView 컨트롤에 표시합니다. 사용자가 CompanyName
열의 셀을 편집하고 셀을 나가려고 하면 CellValidating 이벤트 처리기가 새 회사 이름 문자열을 검사하여 비어 있지 않은지 확인합니다. 새 값이 빈 문자열인 경우 DataGridView에서 비어 있지 않은 문자열이 입력될 때까지 사용자의 커서가 셀을 벗어나지 못하도록 합니다.
이 토픽의 코드를 단일 목록으로 복사하려면 방법: Windows Forms DataGridView 컨트롤의 데이터 유효성 검사를 참조하세요.
사전 요구 사항
이 연습을 완료하려면 다음 사항이 필요합니다.
- Northwind SQL Server 샘플 데이터베이스가 있는 서버에 대한 액세스 권한.
폼 만들기
DataGridView에 입력한 데이터의 유효성 검사
Form에서 파생되고 DataGridView 컨트롤와 BindingSource 구성 요소를 포함하는 클래스를 만듭니다.
다음 코드 예제에서는 기본 초기화를 제공하고
Main
메서드를 포함합니다.using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; public class Form1 : System.Windows.Forms.Form { private DataGridView dataGridView1 = new DataGridView(); private BindingSource bindingSource1 = new BindingSource(); public Form1() { // Initialize the form. this.dataGridView1.Dock = DockStyle.Fill; this.Controls.Add(dataGridView1); this.Load += new EventHandler(Form1_Load); this.Text = "DataGridView validation demo (disallows empty CompanyName)"; }
Imports System.Data Imports System.Data.SqlClient Imports System.Windows.Forms Public Class Form1 Inherits System.Windows.Forms.Form Private WithEvents dataGridView1 As New DataGridView() Private bindingSource1 As New BindingSource() Public Sub New() ' Initialize the form. Me.dataGridView1.Dock = DockStyle.Fill Me.Controls.Add(dataGridView1) Me.Text = "DataGridView validation demo (disallows empty CompanyName)" End Sub
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); } }
<STAThread()> _ Shared Sub Main() Application.EnableVisualStyles() Application.Run(New Form1()) End Sub End Class
데이터베이스 연결의 세부 정보를 처리하기 위한 양식의 클래스 정의에 메서드를 구현합니다.
이 코드 예제에서는 채워진 DataTable 개체를 반환하는
GetData
메서드를 사용합니다.connectionString
변수를 사용자의 데이터베이스에 적합한 값으로 설정해야 합니다.중요
암호와 같은 중요한 정보를 연결 문자열 내에 저장하면 애플리케이션 보안 문제가 발생할 수 있습니다. 데이터베이스 액세스를 제어할 경우에는 통합 보안이라고도 하는 Windows 인증을 사용하는 쪽이 더 안전합니다. 자세한 내용은 연결 정보 보호를 참조하세요.
private static DataTable GetData(string selectCommand) { string connectionString = "Integrated Security=SSPI;Persist Security Info=False;" + "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096"; // Connect to the database and fill a data table. SqlDataAdapter adapter = new SqlDataAdapter(selectCommand, connectionString); DataTable data = new DataTable(); data.Locale = System.Globalization.CultureInfo.InvariantCulture; adapter.Fill(data); return data; }
Private Shared Function GetData(ByVal selectCommand As String) As DataTable Dim connectionString As String = _ "Integrated Security=SSPI;Persist Security Info=False;" + _ "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096" ' Connect to the database and fill a data table. Dim adapter As New SqlDataAdapter(selectCommand, connectionString) Dim data As New DataTable() data.Locale = System.Globalization.CultureInfo.InvariantCulture adapter.Fill(data) Return data End Function
DataGridView 및 Load를 초기화하고 데이터 바인딩을 설정하는 양식의 BindingSource 이벤트에 대한 처리기를 구현합니다.
private void Form1_Load(System.Object sender, System.EventArgs e) { // Attach DataGridView events to the corresponding event handlers. this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating); this.dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit); // Initialize the BindingSource and bind the DataGridView to it. bindingSource1.DataSource = GetData("select * from Customers"); this.dataGridView1.DataSource = bindingSource1; this.dataGridView1.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); }
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Me.Load ' Initialize the BindingSource and bind the DataGridView to it. bindingSource1.DataSource = GetData("select * from Customers") Me.dataGridView1.DataSource = bindingSource1 Me.dataGridView1.AutoResizeColumns( _ DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) End Sub
DataGridView 컨트롤의 CellValidating 및 CellEndEdit 이벤트에 대한 처리기를 구현합니다.
CellValidating 이벤트 처리기에서
CompanyName
열의 셀 값이 비어 있는지 여부를 확인합니다. 셀 값이 유효성 검사에 실패하는 경우 System.Windows.Forms.DataGridViewCellValidatingEventArgs 클래스의 Cancel 속성을true
로 설정합니다. 이렇게 하면 DataGridView 컨트롤이 커서가 셀을 벗어나지 못하도록 합니다. 행의 ErrorText 속성을 설명 문자열로 설정합니다. 오류 텍스트가 포함된 도구 설명이 있는 오류 아이콘이 표시됩니다. CellEndEdit 이벤트 처리기에서 행의 ErrorText 속성을 빈 문자열로 설정합니다. CellEndEdit 이벤트는 셀이 편집 모드를 종료할 때만 발생하며 유효성 검사에 실패할 경우 수행할 수 없습니다.private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { string headerText = dataGridView1.Columns[e.ColumnIndex].HeaderText; // Abort validation if cell is not in the CompanyName column. if (!headerText.Equals("CompanyName")) return; // Confirm that the cell is not empty. if (string.IsNullOrEmpty(e.FormattedValue.ToString())) { dataGridView1.Rows[e.RowIndex].ErrorText = "Company Name must not be empty"; e.Cancel = true; } } void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { // Clear the row error in case the user presses ESC. dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty; }
Private Sub dataGridView1_CellValidating(ByVal sender As Object, _ ByVal e As DataGridViewCellValidatingEventArgs) _ Handles dataGridView1.CellValidating Dim headerText As String = _ dataGridView1.Columns(e.ColumnIndex).HeaderText ' Abort validation if cell is not in the CompanyName column. If Not headerText.Equals("CompanyName") Then Return ' Confirm that the cell is not empty. If (String.IsNullOrEmpty(e.FormattedValue.ToString())) Then dataGridView1.Rows(e.RowIndex).ErrorText = _ "Company Name must not be empty" e.Cancel = True End If End Sub Private Sub dataGridView1_CellEndEdit(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ Handles dataGridView1.CellEndEdit ' Clear the row error in case the user presses ESC. dataGridView1.Rows(e.RowIndex).ErrorText = String.Empty End Sub
애플리케이션 테스트
이제 양식을 테스트하여 예상대로 동작하는지 확인할 수 있습니다.
양식 테스트
애플리케이션을 컴파일하고 실행합니다.
DataGridView가
Customers
표의 데이터로 채워지게 됩니다.CompanyName
열에서 셀을 두 번 클릭하면 값을 편집할 수 있습니다. 모든 문자를 삭제하고 TAB 키를 눌러 셀을 종료하면 DataGridView에서 종료를 방지합니다. 비어 있지 않은 문자열을 셀에 입력하면 DataGridView 컨트롤을 통해 셀을 종료할 수 있습니다.
다음 단계
이 애플리케이션은 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 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기