Only allow numbers in a textbox

  • Thread starter Thread starter Bisley
  • Start date Start date
B

Bisley

I wish to restrict my textbox to only accepting numbers

I have looked the textbox KeyDown event and can inspect KeyEventArgs
parameter and interogate which key has been pressed, but I can't work out
how to stop then stop the character being added to the text box

TIA

Bisley
 
Bisley said:
I wish to restrict my textbox to only accepting numbers

I have looked the textbox KeyDown event and can inspect KeyEventArgs
parameter and interogate which key has been pressed, but I can't work out
how to stop then stop the character being added to the >text box

You can do this by creating your own textbox control that inherits from the
base: System.Windows.Forms.TextBox
and then you will have to override the method: WndProc to handle
WM_CHAR(=0x0102)..

a very simple example that you may extend is:

public class NumTextBox : System.Windows.Forms.TextBox
{
const int WM_CHAR = 0x0102;

private System.ComponentModel.Container components = null;
public NumTextBox()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();

// TODO: Add any initialization after the InitForm call

}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion


protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case WM_CHAR:
if( !char.IsDigit((char)m.WParam) )
{
if((char)m.WParam != 8)//backspace allowness.
{
return ;
}
}

break ;
}
base.WndProc(ref m);
}


}
 
Bisley said:
I wish to restrict my textbox to only accepting numbers

I have looked the textbox KeyDown event and can inspect KeyEventArgs
parameter and interogate which key has been pressed, but I can't work out
how to stop then stop the character being added to the text box

TIA

Bisley

Use "e.Handled = true;" to stop characters being accepted. e.g.:

private void textBox1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
 
I wish to restrict my textbox to only accepting numbers

I have looked the textbox KeyDown event and can inspect KeyEventArgs
parameter and interogate which key has been pressed, but I can't work out
how to stop then stop the character being added to the text box

If you set the event's Handled property to true, that will stop the
character being added. However, I believe you should be handling the
KeyPress event, not KeyDown.
 
Back
Top