TextBox Validation - C#
I am having quite a hard time with my C# Application's tex开发者_StackOverflowtbox validation. The thing is, the said textbox should only accept decimal values. so it means, there should be no letters or any other symbols aside from the '.' symbol. The letter filter, i can handle. However, i don't exactly know how I can manage to filter the number of '.' that the textbox should accept. If anybody has any idea how to do this, please give me an idea.
Thank you very much :)
decimal value;
bool isValid = decimal.TryParse(textBox.Text, out value);
if (!isValid)
{
throw new ArgumentException("Input must be a decimal value");
}
this should work!!!
modified for just one decimal
private void txtType_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back || (e.KeyChar == (char)'.') && !(sender as TextBox).Text.Contains("."))
{
return;
}
decimal isNumber = 0;
e.Handled = !decimal.TryParse(e.KeyChar.ToString(), out isNumber);
}
Use regex validation:
^([0-9]*|\d*\.\d{1}?\d*)$
This site has a library of regex validation (including numeric related) that you'll find useful:
http://regexlib.com/Search.aspx?k=decimal&c=-1&m=-1&ps=20
Just a thought: if you are monitoring the decimal places, simply keep a bool flag in your control to say "I've already had a dot"; subsequent dots are invalid.
Alternatively, when checking for decimal places, you can use Contains
:
if (textbox.Text.Contains("."))
Also, review this sample available on MSDN (NumericTextBox):
http://msdn.microsoft.com/en-us/library/ms229644(VS.80).aspx
Use a MaskedTextBox instead and set the mask to only accept decimals.
精彩评论