Share via


How to: Validate Data in the Windows Forms DataGridView Control

The following code example demonstrates how to validate data entered by a user into a DataGridView control. In this example, the DataGridView is populated with rows from the Customers table of the Northwind sample database. When the user edits a cell in the CompanyName column, its value is tested for validity by checking that it is not empty. If the event handler for the CellValidating event finds that the value is an empty string, the DataGridView prevents the user from exiting the cell until a non-empty string is entered.

For a complete explanation of this code example, see Walkthrough: Validating Data in the Windows Forms DataGridView Control.

Example

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)
        Me.Text = "DataGridView validation demo (disallows empty CompanyName)"

    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_CellValidating(ByVal sender As Object, _
        ByVal e As DataGridViewCellValidatingEventArgs) _
        Handles dataGridView1.CellValidating

        ' Validate the CompanyName entry by disallowing empty strings.
        If dataGridView1.Columns(e.ColumnIndex).Name = "CompanyName" Then
            If String.IsNullOrEmpty(e.FormattedValue.ToString()) Then
                dataGridView1.Rows(e.RowIndex).ErrorText = _
                    "Company Name must not be empty"
                e.Cancel = True
            End If
        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

    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

    <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);
        this.Text = "DataGridView validation demo (disallows empty CompanyName)";
    }

    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 void dataGridView1_CellValidating(object sender,
        DataGridViewCellValidatingEventArgs e)
    {
        // Validate the CompanyName entry by disallowing empty strings.
        if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
        {
            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 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;
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }

}
#using <System.dll>
#using <System.Data.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
#using <System.Xml.dll>
#using <System.EnterpriseServices.dll>
#using <System.Transactions.dll>

using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Windows::Forms;

public ref class Form1 : public System::Windows::Forms::Form
{
private:
    DataGridView^ dataGridView1;
    BindingSource^ bindingSource1;

public:
    Form1()
    {
        dataGridView1 = gcnew DataGridView();
        bindingSource1 = gcnew BindingSource();
        // Initialize the form.
        this->dataGridView1->Dock = DockStyle::Fill;
        this->Controls->Add(dataGridView1);
        this->Load += gcnew EventHandler(this, &Form1::Form1_Load);
    }

private:
    void Form1_Load(System::Object^ /*sender*/, System::EventArgs^ /*e*/)
    {
        // Attach DataGridView events to the corresponding event handlers.
        this->dataGridView1->CellValidating += gcnew
            DataGridViewCellValidatingEventHandler(this, &Form1::dataGridView1_CellValidating);
        this->dataGridView1->CellEndEdit += gcnew
            DataGridViewCellEventHandler(this, &Form1::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:
    void dataGridView1_CellValidating(Object^ /*sender*/,
        DataGridViewCellValidatingEventArgs^ e)
    {
        // Validate the CompanyName entry by disallowing empty strings.
        if (dataGridView1->Columns[e->ColumnIndex]->Name == "CompanyName")
        {
            if (e->FormattedValue->ToString() == String::Empty)
            {
                dataGridView1->Rows[e->RowIndex]->ErrorText =
                    "Company Name must not be empty";
                e->Cancel = true;
            }
        }
    }

private:
    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:
    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 =
            gcnew SqlDataAdapter(selectCommand, connectionString);
        DataTable^ data = gcnew DataTable();
        adapter->Fill(data);

        return data;
    }

public:
    [STAThread]
    static void Main()
    {
        Application::EnableVisualStyles();
        Application::Run(gcnew Form1());
    }
};

int main()
{
    Form1::Main();
}

Compiling the Code

This example requires:

  • References to the System, System.Data, System.Windows.Forms and System.XML assemblies.

For information about building this example from the command line for Visual Basic or Visual C#, see Building from the Command Line (Visual Basic) or Command-Line Building. You can also build this example in Visual Studio by pasting the code into a new project. How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio
How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio
How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio
How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio

Security

Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see Securing Connection Strings.

See Also

Tasks

Walkthrough: Validating Data in the Windows Forms DataGridView Control
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control

Reference

DataGridView
BindingSource

Concepts

Securing Connection Strings

Other Resources

Data Entry in the Windows Forms DataGridView Control