How can I restrict the keystrokes that will be accepted in a column of my datagrid

Platform: WinForms| Category: Datagrid

You can create a custom column style and handle the KeyPress event of its TextBox member. Below is the code showing how this might be done. You can also download a sample project (C#, VB) that shows an implementation of this idea.

public class DataGridDigitsTextBoxColumn : DataGridTextBoxColumn
{
  public DataGridDigitsTextBoxColumn(System.ComponentModel.PropertyDescriptor pd, string format, bool b)
      : base(pd, format, b)
  {
    this.TextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(HandleKeyPress);
  }

  private void HandleKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
  {
    //ignore if not digit or control key
    if(!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
      e.Handled = true;

    //ignore if more than 3 digits
    if(this.TextBox.Text.Length >= 3 && !char.IsControl(e.KeyChar))
      e.Handled = true;
  }

  protected override void Dispose(bool disposing)
  {
    if(disposing)
      this.TextBox.KeyPress -= new System.Windows.Forms.KeyPressEventHandler(HandleKeyPress);

    base.Dispose(disposing);
  }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.