Пример. Проверка данных элемента управления DataGridView в Windows Forms

При отображении функций ввода данных для пользователей вам зачастую приходится проверять данные, введенные в форму. Класс DataGridView предоставляет удобный способ проверки перед фиксацией данных в хранилище данных. Данные можно проверить, обработав событие CellValidating, которое вызывается DataGridView при изменении текущей ячейки.

В этом пошаговом руководстве вы извлечете строки из таблицы Customers в образце базы данных Northwind и отобразите их в элементе управления DataGridView. Когда пользователь изменяет ячейку в столбце CompanyName и пытается выйти из нее, обработчик событий CellValidating проверяет новую строку имени компании, чтобы убедиться, что она не пуста; если новое значение является пустой строкой, DataGridView запрещает вывод курсора пользователя из ячейки, пока вы не войдете в непустую строку.

Чтобы скопировать код в этом разделе в виде единого списка, см. статью Практическое руководство. Проверка данных в DataGridView в Windows Forms.

Необходимые компоненты

Для выполнения задач этого руководства необходимы:

  • Доступ к серверу SQL Server с установленным образцом базы данных Northwind.

Создание формы

Проверка данных, введенных в 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);
            this.Text = "DataGridView validation demo (disallows empty CompanyName)";
        }
    
    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]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }
    
        <STAThread()> _
        Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub
    
    End Class
    
  2. Реализуйте метод в определении класса формы для обработки сведений о подключении к базе данных.

    В этом примере кода используется метод GetData, который возвращает заполненный объект DataTable. Убедитесь, что переменной 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.
        SqlDataAdapter adapter =
            new SqlDataAdapter(selectCommand, connectionString);
        DataTable data = new DataTable();
        data.Locale = System.Globalization.CultureInfo.InvariantCulture;
        adapter.Fill(data);
    
        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.
        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
    
  3. Реализуйте обработчик события Load формы, который инициализирует элементы DataGridView и BindingSource и настраивает привязку данных.

    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);
    }
    
    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. Реализуйте обработчики для событий CellValidating и CellEndEdit элемента управления DataGridView.

    Обработчик событий CellValidating определяет, является ли значение ячейки в столбце CompanyName пустым. Если значение ячейки не проходит проверку, задайте для свойства Cancel класса System.Windows.Forms.DataGridViewCellValidatingEventArgsзначение true. Это приводит к тому, что элемент управления DataGridView запрещает вывод курсора из ячейки. Настройте для свойства ErrorText строки пояснительную строку. Отобразится значок ошибки с подсказкой, содержащей текст ошибки. В обработчике событий CellEndEdit задайте для свойства ErrorTextв строке пустую строку. Событие CellEndEdit возникает только в том случае, если ячейка выходит из режима редактирования, и она не может это сделать, если проверка завершается ошибкой.

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

Тестирование приложения

Теперь можно протестировать форму, чтобы убедиться, что она работает должным образом.

Проверка формы

  • Скомпилируйте и запустите приложение.

    Вы увидите DataGridView, заполненный данными из таблицы Customers. При двойном щелчке на ячейке в столбце CompanyName можно редактировать значение. Если удалить все символы и нажать клавишу табуляции, чтобы выйти из ячейки, DataGridView запретит выходить из нее. При вводе в ячейку непустой строки элемент управления DataGridView позволяет выйти из ячейки.

Дальнейшие действия

Это приложение позволяет получить базовое представление о возможностях элемента управления DataGridView. Внешний вид и поведение элемента управления DataGridView можно настроить несколькими способами:

См. также