Numeric TextBox

  • Thread starter Thread starter Dmitry Karneyev
  • Start date Start date
D

Dmitry Karneyev

How to make TextBox control that allows to input only numerics, currency etc
?
Or can I download such stuff ?
 
If you're not set on the textbox, check out the numericupdown.

If you are set on the textbox, handle the Validating event, set up a try
block and call Decimal.Parse (or whatever type is appropraite to your
scenario). On the exception, cancel the validation.
 
Here is what you need (I hope):

------------------------- CurrencyTextBoxValidator.cs
using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms;


namespace YourApp
{
/// <summary>
/// Summary description for CurrencyTextBoxValidator.
/// </summary>
public class CurrencyTextBoxValidator : System.Windows.Forms.TextBox
{
char keyCharValue;

public CurrencyTextBoxValidator()
{
InitializeComponent();
}

#region Initialize
private void InitializeComponent()
{
this.KeyPress += new
System.Windows.Forms.KeyPressEventHandler(this.CurrencyTextBox_KeyPress);
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.TextChanged += new EventHandler(this.CurrencyTextBox_TextChanged);
}
#endregion

#region public methods

/// <summary>
/// Get the Currency Value (without space) of the TextBox
/// </summary>
/// <returns> -1 when an error occurs</returns>
public int GetValueOfCurrency()
{
try
{
if (this.Text != "")
return (Convert.ToInt32(this.Text.Replace(" ", "")));
else
return -1;
}
catch(Exception)
{
return -1;
}
}

/// <summary>
/// Take the Currency Value (without space) and put it in the TextBox
/// </summary>
public void PutCurrencyIn(string currencyValue)
{
this.Text = currencyValue;
AddSpaceInNumber();
}

#endregion

#region private methods
private void AddSpaceInNumber()
{
for (int posOfSpaceInText = this.Text.Length; posOfSpaceInText > 3;
posOfSpaceInText -= 3)
this.Text = this.Text.Insert(posOfSpaceInText - 3, " ");
}
#endregion

#region mask handlers
private void CurrencyTextBox_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
keyCharValue = e.KeyChar;
}

private void CurrencyTextBox_TextChanged(object sender, System.EventArgs
e)
{
this.TextChanged -= new EventHandler(this.CurrencyTextBox_TextChanged);
if (!Char.IsDigit(keyCharValue) && keyCharValue != ' ' &&
Convert.ToInt32(keyCharValue) != 8)
{
this.Text = this.Text.Replace(keyCharValue.ToString(), "");
this.Select(this.Text.Length, 0);
}
else
{
this.SuspendLayout();
this.Text = this.Text.Replace(" ", "");
AddSpaceInNumber();
this.Select(this.Text.Length, 0);
this.ResumeLayout();
}
this.TextChanged += new EventHandler(this.CurrencyTextBox_TextChanged);
}
#endregion

}
}
 
Great stuff!
There is one another little thing.
This control doesn't allow to inut values with dot, I mean "123.456"
It would be cool to implement such functionality.

But anyway, thanks!
 
I need such control to bind numeric data from database withWindows Form.
Just for intersest: here is modified version of this control with "123,456"
functionality.

using System;

using System.ComponentModel;

using System.Collections;

using System.Diagnostics;

using System.Windows.Forms;

namespace YourApp

{

/// <summary>

/// Summary description for NumericTextBox.

/// </summary>

public class NumericTextBox : System.Windows.Forms.TextBox

{

/// <summary>

/// Required designer variable.

/// </summary>

private System.ComponentModel.Container components = null;

public NumericTextBox()

{

// This call is required by the Windows.Forms Form Designer.

InitializeComponent();

// TODO: Add any initialization after the InitializeComponent 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();

this.KeyPress += new
System.Windows.Forms.KeyPressEventHandler(this.NumericTextBox_KeyPress);

//this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.TextChanged += new EventHandler(this.NumericTextBox_TextChanged);

}

#endregion


char keyCharValue;


protected void NumericTextBox_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)

{

keyCharValue = e.KeyChar;

// we are not going to continue hadling ','

if(e.KeyChar == ',')

{

e.Handled = true;

}

}

/// <summary>

/// Inserting ',' into Text property instead of '.'

/// </summary>

protected void DoDotStuff()

{

int dotPosition = this.Text.LastIndexOf(".");

int sepPosition = this.Text.IndexOf(",");

// ÅÓÌÉ ÔÏÞËÕ ××ÅÌÉ ÎÅ × ÎÁÞÁÌÅ ÓÔÒÏËÉ É ÄÏ ÜÔÏÇÏ ÔÏÖÅ ÎÅ ÂÙÌÏ ××ÅÄÅÎÏ ÔÏÞÅË

if((dotPosition > 0) && (sepPosition < 0))

{

this.Text = this.Text.Replace(keyCharValue.ToString(), ",");

this.Select(this.Text.Length, 0);

}

// ÕÄÁÌÑÅÍ ÔÏ, ÞÔÏ ××ÅÌÉ

else

{

if((sepPosition > 0) && (dotPosition > 0))

{

this.Text = this.Text.Remove(sepPosition, 1);

this.Text = this.Text.Replace(keyCharValue.ToString(), ",");

this.Select(dotPosition, 0);

}

else

{

this.Text = this.Text.Remove(dotPosition, 1);

this.Select(sepPosition, 0);

}

}

}

// private void DoSepStuff()

// {

// int anotherSepPosition = this.Text.LastIndexOf(",");

// int sepPosition = this.Text.IndexOf(",");

// // ÅÓÌÉ ÐÏ×ÔÏÒÎÙÊ ××ÏÄ ÚÁÐÑÔÏÊ ÉÌÉ ÏÎÁ ÐÅÒ×ÁÑ × ÓÔÒÏËÅ

// if((anotherSepPosition != sepPosition) || (sepPosition == 0))

// {

// this.Text = this.Text.Remove(sepPosition, 1);

// this.Select(anotherSepPosition, 0);

// }

// }

protected void NumericTextBox_TextChanged(object sender, System.EventArgs e)

{

this.TextChanged -= new EventHandler(this.NumericTextBox_TextChanged);

this.SuspendLayout();

if (!Char.IsDigit(keyCharValue))

{

switch (keyCharValue)

{

case '.':

DoDotStuff();

break;

default:

// removing that which was inserted

int badCharacterPosition = this.Text.IndexOf(keyCharValue.ToString());

this.Text = this.Text.Replace(keyCharValue.ToString(), "");

this.Select(badCharacterPosition, 0);

break;

}

}

else

{

this.Text = this.Text.Replace(" ", "");

this.Select(this.Text.Length, 0);

}

this.ResumeLayout();

this.TextChanged += new EventHandler(this.NumericTextBox_TextChanged);

}

/// <summary>

/// Get the Currency Value (without space) of the TextBox

/// </summary>

/// <returns> -1 when an error occurs</returns>

public decimal GetValueOfCurrency()

{

try

{

if (this.Text != "")

return (Convert.ToDecimal(this.Text.Replace(" ", "")));

else

return -1;

}

catch(Exception)

{

return -1;

}

}

/// <summary>

/// Take the Currency Value (without space) and put it in the TextBox

/// </summary>

public void PutDecimalIn(decimal decimalValue)

{

try

{

this.Text = decimalValue.ToString();

}

catch(Exception)

{

this.Text = "";

}

}

}

}
 
Helo,

All you have to do is override CreateParams property , below you will find
the code for this class, it's derived from TextBox and only redefine that
property.
Note, this do not check the value you create the control with, only the
input from the user.


public class NumericTextBox : TextBox

{

protected override CreateParams CreateParams

{

get

{

CreateParams cp = base.CreateParams;

cp.Style |= 0x2000; // ES_NUMBER ( defined in WinUser.h )

return cp;

}

}

}

Hope this help,
 
Back
Top