|
5.15 How can I restrict the keystrokes that will be accepted in a column of my 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)
|
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))
|
//ignore if more than 3 digits
|
if(this.TextBox.Text.Length >= 3 && !char.IsControl(e.KeyChar))
|
protected override void Dispose(bool disposing)
|
this.TextBox.KeyPress -= new System.Windows.Forms.KeyPressEventHandler(HandleKeyPress);
|
|
|
|