다음을 통해 공유


연습: Windows Forms DataGridView 컨트롤의 데이터 유효성 검사

데이터 입력 기능을 사용자에게 표시할 때 폼에 입력되는 데이터의 유효성을 검사해야 하는 경우가 많습니다. DataGridView 클래스는 데이터가 데이터 저장소에 커밋되기 전에 유효성 검사를 수행할 수 있는 편리한 방법을 제공합니다. CellValidating 이벤트를 처리하여 데이터의 유효성을 검사할 수 있으며, 이 이벤트는 현재 셀이 바뀔 때 DataGridView에 의해 발생됩니다.

이 연습에서는 Northwind 샘플 데이터베이스의 Customers 테이블에서 행을 검색한 후 검색된 행을 DataGridView 컨트롤에 표시합니다. 사용자가 CompanyName 열의 셀을 편집한 후 셀을 벗어나려고 할 때 CellValidating 이벤트 처리기는 새 회사 이름 문자열이 빈 문자열이 아닌지 확인합니다. 그런 다음 새 값이 빈 문자열이면 DataGridView는 비어 있지 않은 문자열이 입력될 때까지 사용자의 커서를 해당 셀에 유지합니다.

이 항목의 코드를 단일 목록으로 복사하려면 방법: Windows Forms DataGridView 컨트롤의 데이터 유효성 검사를 참조하십시오.

사전 요구 사항

이 연습을 완료하려면 다음과 같은 요건이 필요합니다.

  • Northwind SQL Server 샘플 데이터베이스가 있는 서버에 액세스할 수 있어야 합니다.

폼 만들기

DataGridView에 입력한 데이터의 유효성을 검사하려면

  1. Form에서 파생되고 DataGridView 컨트롤 및 BindingSource 구성 요소를 포함하는 클래스를 만듭니다.

    다음 코드 예제에서는 기본적인 초기화를 제공하고 Main 메서드를 포함합니다.

    Imports System
    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()> _
        Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub
    
    End Class
    
    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)";
        }
    
    
    ...
    
    
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    
    }
    
  2. 데이터베이스에 연결하는 데 필요한 세부 사항을 처리하는 메서드를 폼의 클래스 정의에 구현합니다.

    이 코드 예제에서는 채워진 DataTable 개체를 반환하는 GetData 메서드를 사용합니다. connectionString 변수를 데이터베이스에 해당하는 값으로 설정해야 합니다.

    보안 정보보안 정보

    연결 문자열에 중요한 정보(예: 암호)를 저장하면 응용 프로그램 보안 문제가 발생할 수 있습니다. 데이터베이스 액세스를 제어할 경우에는 통합 보안이라고도 하는 Windows 인증을 사용하는 방법이 더 안전합니다. 자세한 내용은 연결 정보 보호(ADO.NET)를 참조하십시오.

    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
    
    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;
    }
    
  3. DataGridViewBindingSource를 초기화하고 데이터 바인딩을 설정하도록 폼의 Load 이벤트에 대한 처리기를 구현합니다.

    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
    
    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);
    }
    
  4. DataGridView 컨트롤의 CellValidatingCellEndEdit 이벤트 처리기를 구현합니다.

    CellValidating 이벤트 처리기에서는 CompanyName 열의 셀 값이 비어 있는지 여부를 확인합니다. 셀 값의 유효성 검사가 실패한 경우 System.Windows.Forms.DataGridViewCellValidatingEventArgs 클래스의 Cancel 속성을 true로 설정합니다. 이렇게 하면 DataGridView 컨트롤이 커서가 셀을 벗어나지 않도록 합니다. 행의 ErrorText 속성을 설명 문자열로 설정합니다. 이렇게 하면 오류 텍스트가 포함된 도구 설명과 함께 오류 아이콘이 표시됩니다. CellEndEdit 이벤트 처리기에서 행의 ErrorText 속성을 빈 문자열로 설정합니다. CellEndEdit 이벤트는 유효성 검사가 실패하여 편집 모드를 종료할 수 없는 셀이 편집 모드를 종료하는 경우에만 발생합니다.

    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
    
    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;
    }
    

응용 프로그램 테스트

이제 폼을 테스트하여 예상한 대로 동작하는지 확인할 수 있습니다.

폼을 테스트하려면

  • 응용 프로그램을 컴파일하여 실행합니다.

    Customers 테이블의 데이터로 채워진 DataGridView가 표시됩니다. CompanyName 열의 셀을 두 번 클릭하면 셀의 값을 편집할 수 있습니다. 모든 문자를 삭제하고 Tab 키를 눌러 셀을 종료하면 DataGridView는 셀이 종료되지 않도록 합니다. 비어 있지 않은 문자열을 셀에 입력하면 DataGridView 컨트롤은 셀 종료를 허용합니다.

다음 단계

이 응용 프로그램은 DataGridView 컨트롤의 기능에 대한 기본적인 이해를 제공합니다. 다음과 같은 여러 가지 방법으로 DataGridView 컨트롤의 모양과 동작을 사용자 지정할 수 있습니다.

참고 항목

작업

방법: Windows Forms DataGridView 컨트롤의 데이터 유효성 검사

연습: Windows Forms DataGridView 컨트롤에서 데이터 입력 중에 발생하는 오류 처리

참조

DataGridView

BindingSource

개념

연결 정보 보호(ADO.NET)

기타 리소스

Windows Forms DataGridView 컨트롤의 데이터 입력