473,327 Members | 2,065 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

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 16175
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.com> wrote in message
news:ut**************@TK2MSFTNGP09.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):

------------------------- 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.Cur rencyTextBox_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

}
}

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

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

"Dmitry Karneyev" <ka******@msn.com> wrote in message
news:ut**************@TK2MSFTNGP09.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.org> сообщил/сообщила в новостях
следующее: news:OR**************@TK2MSFTNGP09.phx.gbl...
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.Cur rencyTextBox_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

}
}

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

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

"Dmitry Karneyev" <ka******@msn.com> wrote in message
news:ut**************@TK2MSFTNGP09.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.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.Num ericTextBox_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 = "";

}

}

}

}
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.CreateParams;

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.com> wrote in message
news:ut**************@TK2MSFTNGP09.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
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...
11
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...
20
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...
4
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...
3
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 ...
0
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...
5
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...
3
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,...
4
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
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you▓ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.