Share via


HOW TO:處理 Windows Form DataGridView 控制項中的資料輸入期間所發生的錯誤

更新:2007 年 11 月

下列程式碼範例示範如何使用 DataGridView 控制項,向使用者報告資料輸入錯誤。

如需這個程式碼範例的完整說明,請參閱逐步解說:處理 Windows Form DataGridView 控制項中的資料輸入期間所發生的錯誤

範例

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

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

}

編譯程式碼

這項範例需要:

  • System、System.Data、System.Windows.Forms 和 System.XML 組件的參考。

如需從 Visual Basic 或 Visual C# 的命令列建置這個範例的詳細資訊,請參閱從命令列建置 (Visual Basic)使用 csc.exe 建置命令列。您也可以透過將程式碼貼入新的專案,在 Visual Studio 中建置此範例。

安全性

在連接字串內儲存機密資訊 (例如密碼) 會影響應用程式的安全性。使用 Windows 驗證 (也稱為整合式安全性) 是控制資料庫存取的更安全方式。如需詳細資訊,請參閱保護連接資訊 (ADO.NET)

請參閱

工作

逐步解說:處理 Windows Form DataGridView 控制項中的資料輸入期間所發生的錯誤

逐步解說:驗證 Windows Form DataGridView 控制項中的資料

概念

保護連接資訊 (ADO.NET)

參考

DataGridView

BindingSource

其他資源

Windows Form DataGridView 控制項中的資料輸入