1 Previous Next 

DataGrid: Validate data entered into textboxcolumn


Be aware this tip is for the Windows Forms DataGrid, not for the DataGridView
To validate the text entered into a datagrid add a handler to the DatagridTextboxColumn's validating event. Here is some sample code.


    Dim ds As New DataSet

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim conn As SqlConnection
        Dim strConn As String
        Dim strSQL As String
        Dim da As SqlDataAdapter

        strConn = "Server = (local);"
        strConn &= "Database = NorthWind;"
        strConn &= "Integrated Security = SSPI;"


        conn = New SqlConnection(strConn)
        da = New SqlDataAdapter("Select * From Products", conn)
        da.Fill(ds, "Products")


        Dim ts As New DataGridTableStyle
        ts.MappingName = ds.Tables("Products").TableName

        Dim colDiscontinued As New DataGridBoolColumn
        With colDiscontinued
            .MappingName = "Discontinued"
            .HeaderText = "Discontinued"
            .Width = 80
        End With

        Dim colName As New DataGridTextBoxColumn
        With colName
            .MappingName = "ProductName"
            .HeaderText = "Product Name"
            .Width = 180
        End With
        AddHandler colName.TextBox.Validating, AddressOf CellValidating


        ts.GridColumnStyles.Add(colName)
        ts.GridColumnStyles.Add(colDiscontinued)

        DataGrid1.TableStyles.Add(ts)

        ts = Nothing
        colDiscontinued = Nothing
        colName = Nothing


        DataGrid1.DataSource = ds.Tables("Products")
    End Sub

    Private Sub CellValidating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
        Debug.WriteLine(DirectCast(sender, DataGridTextBox).Text)
    End Sub



1 Previous Next