Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

5. Windows Forms Datagrid

5.81 How can I use events to restrict key input to grid cells?


If you make sure your DataGrid is using a DataGridTableStyle, then you can access the TextBox through the GridColumnStyles collection and hook the event there. Here is some code....

[C#]
     //in formload
     this.dataGrid2.DataSource = this.dataSet11.Customers; // set the data source

     //make sure grid has a tablestyle
     DataGridTableStyle ts = new DataGridTableStyle();
     ts.MappingName = this.dataSet11.Customers.TableName;
     this.dataGrid2.TableStyles.Add(ts);

     //now we can wire up wire up events for columns 1 and 4 ....
     DataGridTextBoxColumn tbc = (DataGridTextBoxColumn)ts.GridColumnStyles[0];
     tbc.TextBox.KeyPress += new KeyPressEventHandler(CellKeyPress);

     tbc = (DataGridTextBoxColumn)ts.GridColumnStyles[3];
     tbc.TextBox.KeyPress += new KeyPressEventHandler(CellKeyPress);.....

     //the handler
     private void CellKeyPress(object sender, KeyPressEventArgs e)
     {
          //don't allow 1's
          if(e.KeyChar == '1')
          e.Handled = true;
     }

[VB.NET]
      'in formload
     Me.dataGrid2.DataSource = Me.dataSet11.Customers ' set the data source
     
     'make sure grid has a tablestyle
     Dim ts As New DataGridTableStyle()
     ts.MappingName = Me.dataSet11.Customers.TableName
     Me.dataGrid2.TableStyles.Add(ts)

     'now we can wire up wire up events for columns 1 and 4 ....
     Dim tbc as DataGridTextBoxColumn = CType(ts.GridColumnStyles(0), DataGridTextBoxColumn)
     AddHandler tbc.TextBox.KeyPress, AddressOf CellKeyPress

     tbc = CType(ts.GridColumnStyles(3), DataGridTextBoxColumn)
     AddHandler tbc.TextBox.KeyPress, AddressOf CellKeyPress
     .....

     'the handler
     Private Sub CellKeyPress(sender As Object, e As KeyPressEventArgs)
          'don't allow 1's
          If e.KeyChar = "1"c Then
               e.Handled = True
          End If
     End Sub 'CellKeyPress