방법: Windows Forms DataGridView 컨트롤에서 데이터 입력 중에 발생하는 오류 처리
다음 코드 예제에서는 DataGridView 컨트롤을 사용하여 데이터 입력 오류를 사용자에게 보고하는 방법을 보여 줍니다.
이 코드 예에 대한 자세한 설명은 연습: Windows Forms DataGridView 컨트롤에서 데이터 입력 중에 발생하는 오류 처리를 참조하세요.
예제
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);
}
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 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 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;
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
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
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 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 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
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
코드 컴파일
이 예제에는 다음 사항이 필요합니다.
- System, System.Data, System.Windows.Forms 및 System.XML 어셈블리에 대한 참조
.NET Framework 보안
암호와 같은 중요한 정보를 연결 문자열 내에 저장하면 애플리케이션 보안 문제가 발생할 수 있습니다. 데이터베이스 액세스를 제어할 경우에는 통합 보안이라고도 하는 Windows 인증을 사용하는 방법이 더 안전합니다. 자세한 내용은 연결 정보 보호를 참조하세요.
참고 항목
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET Desktop feedback
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기