473,606 Members | 2,200 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Numeric TextBox

How to make TextBox control that allows to input only numerics, currency etc
?
Or can I download such stuff ?
Nov 15 '05 #1
5 16189
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.

--

Justin Weinberg
Designing a PrintDocument? Drawing to forms?
Check out GDI+ Architect at www.mrgsoft.com
"Dmitry Karneyev" <ka******@msn.c om> wrote in message
news:ut******** ******@TK2MSFTN GP09.phx.gbl...
How to make TextBox control that allows to input only numerics, currency etc ?
Or can I download such stuff ?

Nov 15 '05 #2
Here is what you need (I hope):

------------------------- CurrencyTextBox Validator.cs
using System;
using System.Componen tModel;
using System.Collecti ons;
using System.Diagnost ics;
using System.Windows. Forms;
namespace YourApp
{
/// <summary>
/// Summary description for CurrencyTextBox Validator.
/// </summary>
public class CurrencyTextBox Validator : System.Windows. Forms.TextBox
{
char keyCharValue;

public CurrencyTextBox Validator()
{
InitializeCompo nent();
}

#region Initialize
private void InitializeCompo nent()
{
this.KeyPress += new
System.Windows. Forms.KeyPressE ventHandler(thi s.CurrencyTextB ox_KeyPress);
this.BorderStyl e = System.Windows. Forms.BorderSty le.FixedSingle;
this.TextChange d += new EventHandler(th is.CurrencyText Box_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 GetValueOfCurre ncy()
{
try
{
if (this.Text != "")
return (Convert.ToInt3 2(this.Text.Rep lace(" ", "")));
else
return -1;
}
catch(Exception )
{
return -1;
}
}

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

#endregion

#region private methods
private void AddSpaceInNumbe r()
{
for (int posOfSpaceInTex t = this.Text.Lengt h; posOfSpaceInTex t > 3;
posOfSpaceInTex t -= 3)
this.Text = this.Text.Inser t(posOfSpaceInT ext - 3, " ");
}
#endregion

#region mask handlers
private void CurrencyTextBox _KeyPress(objec t sender,
System.Windows. Forms.KeyPressE ventArgs e)
{
keyCharValue = e.KeyChar;
}

private void CurrencyTextBox _TextChanged(ob ject sender, System.EventArg s
e)
{
this.TextChange d -= new EventHandler(th is.CurrencyText Box_TextChanged );
if (!Char.IsDigit( keyCharValue) && keyCharValue != ' ' &&
Convert.ToInt32 (keyCharValue) != 8)
{
this.Text = this.Text.Repla ce(keyCharValue .ToString(), "");
this.Select(thi s.Text.Length, 0);
}
else
{
this.SuspendLay out();
this.Text = this.Text.Repla ce(" ", "");
AddSpaceInNumbe r();
this.Select(thi s.Text.Length, 0);
this.ResumeLayo ut();
}
this.TextChange d += new EventHandler(th is.CurrencyText Box_TextChanged );
}
#endregion

}
}

------------------------
Best regards.

--
Aymeric GAURAT APELLI
Consultant 3IE (http://www.3ie.org)

"Dmitry Karneyev" <ka******@msn.c om> wrote in message
news:ut******** ******@TK2MSFTN GP09.phx.gbl...
How to make TextBox control that allows to input only numerics, currency etc ?
Or can I download such stuff ?

Nov 15 '05 #3
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!

"Aymeric GAURAT APELLI" <ga******@3ie.o rg> сообщил/сообщила в новостях
следующее: news:OR******** ******@TK2MSFTN GP09.phx.gbl...
Here is what you need (I hope):

------------------------- CurrencyTextBox Validator.cs
using System;
using System.Componen tModel;
using System.Collecti ons;
using System.Diagnost ics;
using System.Windows. Forms;
namespace YourApp
{
/// <summary>
/// Summary description for CurrencyTextBox Validator.
/// </summary>
public class CurrencyTextBox Validator : System.Windows. Forms.TextBox
{
char keyCharValue;

public CurrencyTextBox Validator()
{
InitializeCompo nent();
}

#region Initialize
private void InitializeCompo nent()
{
this.KeyPress += new
System.Windows. Forms.KeyPressE ventHandler(thi s.CurrencyTextB ox_KeyPress);
this.BorderStyl e = System.Windows. Forms.BorderSty le.FixedSingle;
this.TextChange d += new EventHandler(th is.CurrencyText Box_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 GetValueOfCurre ncy()
{
try
{
if (this.Text != "")
return (Convert.ToInt3 2(this.Text.Rep lace(" ", "")));
else
return -1;
}
catch(Exception )
{
return -1;
}
}

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

#endregion

#region private methods
private void AddSpaceInNumbe r()
{
for (int posOfSpaceInTex t = this.Text.Lengt h; posOfSpaceInTex t > 3;
posOfSpaceInTex t -= 3)
this.Text = this.Text.Inser t(posOfSpaceInT ext - 3, " ");
}
#endregion

#region mask handlers
private void CurrencyTextBox _KeyPress(objec t sender,
System.Windows. Forms.KeyPressE ventArgs e)
{
keyCharValue = e.KeyChar;
}

private void CurrencyTextBox _TextChanged(ob ject sender, System.EventArg s
e)
{
this.TextChange d -= new EventHandler(th is.CurrencyText Box_TextChanged );
if (!Char.IsDigit( keyCharValue) && keyCharValue != ' ' &&
Convert.ToInt32 (keyCharValue) != 8)
{
this.Text = this.Text.Repla ce(keyCharValue .ToString(), "");
this.Select(thi s.Text.Length, 0);
}
else
{
this.SuspendLay out();
this.Text = this.Text.Repla ce(" ", "");
AddSpaceInNumbe r();
this.Select(thi s.Text.Length, 0);
this.ResumeLayo ut();
}
this.TextChange d += new EventHandler(th is.CurrencyText Box_TextChanged );
}
#endregion

}
}

------------------------
Best regards.

--
Aymeric GAURAT APELLI
Consultant 3IE (http://www.3ie.org)

"Dmitry Karneyev" <ka******@msn.c om> wrote in message
news:ut******** ******@TK2MSFTN GP09.phx.gbl...
How to make TextBox control that allows to input only numerics, currency

etc
?
Or can I download such stuff ?


Nov 15 '05 #4
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.Componen tModel;

using System.Collecti ons;

using System.Diagnost ics;

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.Componen tModel.Containe r components = null;

public NumericTextBox( )

{

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

InitializeCompo nent();

// TODO: Add any initialization after the InitializeCompo nent call

}

/// <summary>

/// Clean up any resources being used.

/// </summary>

protected override void Dispose( bool disposing )

{

if( disposing )

{

if(components != null)

{

components.Disp ose();

}

}

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 InitializeCompo nent()

{

components = new System.Componen tModel.Containe r();

this.KeyPress += new
System.Windows. Forms.KeyPressE ventHandler(thi s.NumericTextBo x_KeyPress);

//this.BorderStyl e = System.Windows. Forms.BorderSty le.FixedSingle;

this.TextChange d += new EventHandler(th is.NumericTextB ox_TextChanged) ;

}

#endregion
char keyCharValue;
protected void NumericTextBox_ KeyPress(object sender,
System.Windows. Forms.KeyPressE ventArgs 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.LastI ndexOf(".");

int sepPosition = this.Text.Index Of(",");

// если точку ввели не в начале строки и до этого тоже не было введено точек

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

{

this.Text = this.Text.Repla ce(keyCharValue .ToString(), ",");

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

}

// удаляем то, что ввели

else

{

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

{

this.Text = this.Text.Remov e(sepPosition, 1);

this.Text = this.Text.Repla ce(keyCharValue .ToString(), ",");

this.Select(dot Position, 0);

}

else

{

this.Text = this.Text.Remov e(dotPosition, 1);

this.Select(sep Position, 0);

}

}

}

// private void DoSepStuff()

// {

// int anotherSepPosit ion = this.Text.LastI ndexOf(",");

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

// // если повторный ввод запятой или она первая в строке

// if((anotherSepP osition != sepPosition) || (sepPosition == 0))

// {

// this.Text = this.Text.Remov e(sepPosition, 1);

// this.Select(ano therSepPosition , 0);

// }

// }

protected void NumericTextBox_ TextChanged(obj ect sender, System.EventArg s e)

{

this.TextChange d -= new EventHandler(th is.NumericTextB ox_TextChanged) ;

this.SuspendLay out();

if (!Char.IsDigit( keyCharValue))

{

switch (keyCharValue)

{

case '.':

DoDotStuff();

break;

default:

// removing that which was inserted

int badCharacterPos ition = this.Text.Index Of(keyCharValue .ToString());

this.Text = this.Text.Repla ce(keyCharValue .ToString(), "");

this.Select(bad CharacterPositi on, 0);

break;

}

}

else

{

this.Text = this.Text.Repla ce(" ", "");

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

}

this.ResumeLayo ut();

this.TextChange d += new EventHandler(th is.NumericTextB ox_TextChanged) ;

}

/// <summary>

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

/// </summary>

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

public decimal GetValueOfCurre ncy()

{

try

{

if (this.Text != "")

return (Convert.ToDeci mal(this.Text.R eplace(" ", "")));

else

return -1;

}

catch(Exception )

{

return -1;

}

}

/// <summary>

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

/// </summary>

public void PutDecimalIn(de cimal decimalValue)

{

try

{

this.Text = decimalValue.To String();

}

catch(Exception )

{

this.Text = "";

}

}

}

}
Nov 15 '05 #5
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.CreatePara ms;

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

return cp;

}

}

}

Hope this help,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Dmitry Karneyev" <ka******@msn.c om> wrote in message
news:ut******** ******@TK2MSFTN GP09.phx.gbl...
How to make TextBox control that allows to input only numerics, currency etc ?
Or can I download such stuff ?

Nov 15 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1121
by: Phillip Ian | last post by:
I have a textbox that I'm trying to limit to numeric entry (damn you Microsoft for not including it in .NET!) I've found sample code and come up with this as a solution: <asp:TextBox id="fldQty" runat="server" CssClass="ThreePlaceInput" MaxLength="3" Text='<%# DataBinder.Eval(Container, "DataItem.Qty") %>' onKeyPress="javascript:return AllowOnlyNumbers();"> The Javascript looks like this:
11
4534
by: Keith | last post by:
I apologize for those of you who think I'm posting on the same topic. It is not that I don't appreciate all of your comments - and I'm definitely reading them all - but I think I have a differing opinion of how I want to handle the 'user experience' in the application I'm creating. While I know I could allow the user to enter in number and alpha text - in a text box - and then tell them when the execuate a command "This is not numeric data", I...
20
2031
by: Keith | last post by:
The following control code - only allows for the entry of numbers, backspace, and decimals (or periods). The problem lies in the last statement - it allows multiple decimals or periods. How would I modify the code to only allow 1 decimal? In other words - once a user entered one period - no others could be entered? Private Overloads Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As...
4
1949
by: dzemo | last post by:
hi i have tis procedure for my text box Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress If Char.IsDigit(e.KeyChar) Then e.Handled = False Else e.Handled = True End If End Sub
3
6676
by: Aaron Smith | last post by:
I found an quick and dirty example of a numeric text box that converts the string to a currency mask.. Here is the code: Public Class NumericMaskedTextBox Inherits System.Windows.Forms.TextBox Private Sub NumericMaskedTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress 'the key press is not in the string (of numerals) If InStr(1, "0123456789.", e.KeyChar,...
0
1123
by: bijuvarghese576 | last post by:
I made a user control in which i used a textbox which accepts only numeric only. I tested and it is working fine. I used this user control in my FORM and bound it with a data field, it shows value in it, but when i try to modify the value and exit / lost focus from the user control the value did'nt change, it agains shows the initial value (i.e the value from the data already in the user control when the FORM loads) How can i modify the...
5
2075
by: siri11 | last post by:
Hi!!!!!!!!!!!!!!! Can anyone please suggest how to customise a textbox so that it must accept only numbers and decimal point.And it shud not accept any alphabets & special characters Thanks in advance siri
3
6907
progdoctor
by: progdoctor | last post by:
Friends.. i have a problem.. How to make an input textbox work as desktop application textbox (money format case)? For example: when i entry 99200 in the inputbox and then press enter/tab key, the screen will display 99,200.00 and if i entry 99200.25 the screen will show me 99,200.25 and 0.00 as default value. Anyway Thanks for the guide... Ian
4
1772
by: kpomeru | last post by:
ok i have a textbox say textbox1.text and i want to make sure when a non numeric value is entered it exits sub or does nothing.. thanks
0
8439
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8430
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8094
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8305
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5966
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph DuprИ who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3977
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2448
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1553
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1296
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.