Limit key input to DataGrid cells by using events

The easiest way to restrict the input characters a user can type into textbox cells on a DataGrid is to use a DataGridTableStyle and to add a GridColumnStyle for each column in the grid. Then you can access the textbox and hook the KeyPress event.

Retrieve the "Customers" data using a DataAdapter and call the DataAdapter's Fill method to populate the DataSet.

For the VB.NET coder:

    Imports System.Data.OleDb

    Dim strSQL As String = "Select * From Customers"
    Dim Connection As New OleDbConnection(strConnection)
    Dim DA As New OleDbDataAdapter(strSQL, Connection)
    Dim DS As New DataSet

    DA.Fill(DS, "Customers")

Format the DataGrid by adding a DataGrid Table Style.

    '
    ' Create a Grid Table Style. Map it to the "Customers" Table.
    '
    Dim aGridTableStyle As New DataGridTableStyle
    aGridTableStyle.MappingName = "Customers"
    '
    ' Create GridColumnStyle objects for the grid columns 
    '
    Dim aCol1 As New DataGridTextBoxColumn
    Dim aCol2 As New DataGridTextBoxColumn
    Dim aCol3 As New DataGridTextBoxColumn
    '
    ' Hide column 1 by setting its width to 0.
    '
    With aCol1
        .MappingName = "Customer_ID"
        .Width = 0
    End With
    '
    ' Set column 2's caption, width and disable editing.
    '
    With aCol2
        .MappingName = "Customer_Name"
        .HeaderText = "Customer"
        .Width = 65
        .Alignment = HorizontalAlignment.Left
        .TextBox.Enabled = True
    End With
    '
    ' Set column 3's caption, width and enable editing.
    ' Since this values is optional set its Null value.
    '
    With aCol3
        .MappingName = "Last_Order_Date"
        .HeaderText = "Order Date"
        .Width = 50
        .Alignment = HorizontalAlignment.Center
        .NullText = ""
        .TextBox.Enabled = True
        .Format = "yyyy-MM-dd"
    End With
    '
    ' Add the GridColumnStyles to the DataGrid's Column Styles collection.
    ' Place the "ID" column (column 1) last since it is not visible.
    '
    With aGridTableStyle.GridColumnStyles
        .Add(aCol2)
        .Add(aCol3)
        .Add(aCol1)
    End With
    '
    ' Tie our keypress handler to the textbox's KeyPress event.
    '
    Dim tbc As DataGridTextBoxColumn = _
            CType(aGridTableStyle.GridColumnStyles(2), DataGridTextBoxColumn) 
    AddHandler tbc.TextBox.KeyPress, AddressOf DateKeyPress 
    '
    ' Add the GridColumnStyles to the aGridTableStyle.
    '
    DataGrid.TableStyles.Add(aGridTableStyle)

    '
    ' Keypress handler for date values.
    '
    Private Sub DateKeyPress(sender As object, e As KeyPressEventArgs) 
        Select Asc(e.KeyChar)
            Case AscW(ControlChars.Cr)   'Enter key
                e.Handled = True
            Case AscW(ControlChars.Back) 'Backspace            
            Case 45          'Dash
            Case 48 To 57 'Numbers 
            Case Else        'Everything else
                e.Handled = True
        End Select
    End Sub

Bind the DataSet to the DataGrid using the DataGrid's DataSource property. Expand the DataGrid's treeview and navigate to first row of the Customers table.

    '
    ' Bind the DataGrid to the DataSet. Expand and navigate to first row.
    '
    If DS.Tables(0).Rows.Count > 0 Then
        With DataGrid
           .DataSource = DS.Tables(0)
           .Expand(-1)
           .NavigateTo(0, "Customers")
        End With
    End If

For the C# coder:

    using System.Data;
    using System.Data.OleDb;

    string strSQL = "Select * From Customers";
    OleDbConnection Connection = new OleDbConnection(strConnection);
    OleDbDataAdapter DA = new OleDbDataAdapter(strSQL, Connection);
    DataSet DS = new DataSet();

    DS = new DataSet();
    DA.Fill(DS, "Customers")
    //
    // Create a Grid Table Style. Map it to the "Customers" Table.
    //
    DataGridTableStyle aGridTableStyle = new DataGridTableStyle();
    aGridTableStyle.MappingName = "Customers";
    //
    // Create GridColumnStyle objects for the grid columns 
    //
    DataGridTextBoxColumn aCol1 = new DataGridTextBoxColumn();
    DataGridTextBoxColumn aCol2 = new DataGridTextBoxColumn();
    DataGridTextBoxColumn aCol3 = new DataGridTextBoxColumn();
    //
    // Hide column 1 by setting its width to 0.
    //
    aCol1.MappingName = "Customer_ID";
    aCol1.Width = 0;
    //
    // Set column 2's caption, width and enable editing.
    //
    aCol2.MappingName = "Customer_Name";
    aCol2.HeaderText = "Customer";
    aCol2.Width = 65;
    aCol2.Alignment = HorizontalAlignment.Left;
    aCol2.TextBox.Enabled = true;
    //
    // Set column 3's caption, width and enable editing.
    // Since this value is optional set its Null value.
    //
    aCol3.MappingName = "Last_Order_Date";
    aCol3.HeaderText = "Order Date";
    aCol3.Width = 50;
    aCol3.Alignment = HorizontalAlignment.Center;
    aCol3.NullText = "";
    aCol3.TextBox.Enabled = true;
    aCol3.Format = "yyyy-MM-dd";
    //
    // Add the GridColumnStyles to the DataGrid's Column Styles collection.
    // Place the "ID" column (column 1) last since it is not visible.
    //
    aGridTableStyle.GridColumnStyles.Add(aCol2);
    aGridTableStyle.GridColumnStyles.Add(aCol3);
    aGridTableStyle.GridColumnStyles.Add(aCol1);
    //
    // Add the GridColumnStyles to the aGridTableStyle.
    //
    DataGrid.TableStyles.Add(aGridTableStyle);
    //
    // Tie our keypress handler to the textbox's KeyPress event.
    //
    DataGridTextBoxColumn tbc = 
       (DataGridTextBoxColumn) aGridTableStyle.GridColumnStyles[2]; 
    tbc.TextBox.KeyPress += new KeyPressEventHandler(DateKeyPress); 
    //
    // Bind the DataGrid to the DataSet. Expand and navigate to first row.
    //
    if (DS.Tables[0].Rows.Count > 0)
    {
        DataGrid.DataSource = DS.Tables[0];
        DataGrid.Expand(-1);
        DataGrid.NavigateTo(0, "Customers");
    }

    //
    // Keypress handler for date values.
    //
    private void DateKeyPress(object sender, KeyPressEventArgs e) 
    { 
        switch ((char)(e.KeyChar))
        {
            case '\r': //Enter key
                e.Handled = true;
                break;           
            case '\b': //Backspace            
            case '-':  //Dash
            case '0':  //Numbers
            case '1': 
            case '2': 
            case '3': 
            case '4': 
            case '5': 
            case '6': 
            case '7': 
            case '8': 
            case '9': 
                break;
            default:   // Everything else
                e.Handled = true;
                break;
        }
    }


About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2016 TheScarms
Goto top of page