다음을 통해 공유


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

기본 데이터 저장소에서 오류를 처리하는 것은 데이터 입력 애플리케이션에 필요한 기능입니다. Windows Forms DataGridView 컨트롤을 사용하면 데이터 저장소에서 제약 조건 위반 또는 손상된 비즈니스 규칙을 감지할 때 발생하는 DataError 이벤트를 노출하여 이 작업을 쉽게 수행할 수 있습니다.

이 연습에서는 Northwind 샘플 데이터베이스의 Customers 표에서 행을 검색하고 이를 DataGridView 컨트롤에 표시합니다. 새 행 또는 편집된 기존 행에서 중복 CustomerID 값이 검색되면 예외를 설명하는 MessageBox 을(를) 표시하여 처리되는 DataError 이벤트가 발생합니다.

이 항목의 코드를 단일 목록으로 복사하려면 방법: Windows Forms DataGridView 컨트롤에서 데이터 입력 중에 발생하는 오류 처리를 참조하세요.

필수 조건

이 절차를 완료하려면 다음이 필요합니다.

  • Northwind SQL Server 샘플 데이터베이스가 있는 서버에 대한 액세스 권한.

폼 만들기

DataGridView 컨트롤에서 데이터 입력 오류를 처리하려면

  1. 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);
        }
    
    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]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }
    
        <STAThread()> _
        Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub
    
    End Class
    
  2. 데이터베이스 연결의 세부 정보를 처리하기 위한 양식의 클래스 정의에 메서드를 구현합니다.

    이 코드 예제에서는 채워진 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, 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;
    }
    
    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
    
  3. DataGridViewLoad를 초기화하고 데이터 바인딩을 설정하는 양식의 BindingSource 이벤트에 대한 처리기를 구현합니다.

    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);
    }
    
    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
    
  4. DataGridView에서 DataError 이벤트를 처리합니다.

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

    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.");
        }
    }
    
    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
    

애플리케이션 테스트

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

양식을 테스트하려면

  • F5 키를 눌러 애플리케이션을 실행합니다.

    Customers 테이블의 데이터로 채워진 DataGridView 컨트롤이 표시됩니다. CustomerID의 중복 값을 입력하고 편집을 커밋하면 셀 값이 자동으로 되돌아가고 데이터 입력 오류를 표시하는 MessageBox볼 수 있습니다.

다음 단계

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

참고하십시오