다음을 통해 공유


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

내부 데이터 저장소의 오류 처리 기능은 데이터 입력 응용 프로그램의 필수 기능입니다. Windows Forms DataGridView 컨트롤을 사용하면 데이터 저장소에서 제약 조건 위반 또는 비즈니스 규칙 위반이 감지될 때 발생하는 DataError 이벤트가 노출되기 때문에 이 작업을 쉽게 수행할 수 있습니다.

이 연습에서는 Northwind 샘플 데이터베이스의 Customers 테이블에서 행을 검색한 후 검색된 행을 DataGridView 컨트롤에 표시합니다. 새 행이나 편집된 기존 행에 중복된 CustomerID 값이 있으면 DataError 이벤트가 발생하는데, 이 이벤트는 예외를 설명하는 MessageBox를 표시함으로써 처리됩니다.

이 항목의 코드를 단일 목록으로 복사하려면 방법: 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)
    
        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);
        }
    
    
    ...
    
    
        [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, including the 
        ' schema information that contains the CustomerID column 
        ' constraint.
        Dim adapter As New SqlDataAdapter(selectCommand, connectionString)
        Dim data As New DataTable()
        data.Locale = System.Globalization.CultureInfo.InvariantCulture
        adapter.Fill(data)
        adapter.FillSchema(data, SchemaType.Source)
    
        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, including the 
        // schema information that contains the CustomerID column 
        // constraint.
        SqlDataAdapter adapter =
            new SqlDataAdapter(selectCommand, connectionString);
        DataTable data = new DataTable();
        data.Locale = System.Globalization.CultureInfo.InvariantCulture;
        adapter.Fill(data);
        adapter.FillSchema(data, SchemaType.Source);
    
        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 the DataError event to the corresponding event handler.
        this.dataGridView1.DataError +=
            new DataGridViewDataErrorEventHandler(dataGridView1_DataError);
    
        // 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. DataGridViewDataError 이벤트를 처리합니다.

    오류 컨텍스트가 커밋 작업인 경우에는 MessageBox에 오류를 표시합니다.

    Private Sub dataGridView1_DataError(ByVal sender As Object, _
        ByVal e As DataGridViewDataErrorEventArgs) _
        Handles dataGridView1.DataError
    
        ' If the data source raises an exception when a cell value is 
        ' commited, display an error message.
        If e.Exception IsNot Nothing AndAlso _
            e.Context = DataGridViewDataErrorContexts.Commit Then
    
            MessageBox.Show("CustomerID value must be unique.")
    
        End If
    
    End Sub
    
    private void dataGridView1_DataError(object sender,
        DataGridViewDataErrorEventArgs e)
    {
        // If the data source raises an exception when a cell value is 
        // commited, display an error message.
        if (e.Exception != null &&
            e.Context == DataGridViewDataErrorContexts.Commit)
        {
            MessageBox.Show("CustomerID value must be unique.");
        }
    }
    

응용 프로그램 테스트

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

폼을 테스트하려면

  • F5 키를 눌러 응용 프로그램을 실행합니다.

    Customers 테이블의 데이터로 채워진 DataGridView 컨트롤이 표시됩니다. CustomerID에 대해 중복 값을 입력하고 편집 내용을 커밋하면 셀 값이 자동으로 복원되고 데이터 입력 오류를 표시하는 MessageBox가 나타납니다.

다음 단계

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

참고 항목

작업

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

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

참조

DataGridView

BindingSource

개념

연결 정보 보호(ADO.NET)

기타 리소스

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