Text input validation for textbox in .NET 4.0 - c#

I want to validate (in some simple way) if the input text for a textbox is a number, I would use this code: LINK
But here's a problem: I use .NET 4.0 not 4.5, so I don't havePreviewTextInput event.
I could use TextChanged, but now it doesn't have e.Handled validator.
Is there any simple solution for this (I want to avoid tons of code)?

If you have access to the property that will hold the value, you can use a DataAnnotation on the property.
[RegularExpression(Pattern="[0-9]+")]
public string MyProperty { get; set; }
This MSDN article goes abit more in depth about the subject.

It is difficult to determine what a number is and isn't. I would use TryParse. If it fails it's not a number.
string s = "12345";
int number;
bool result = int.TryParse(s, out number);
if(!result)
{
// not a number.
}

Related

blazorise numeric edit group separating

I'm trying to use blazorise numeric edit group separating attribute. as it is said in it's documentation it should be possible to use it, but as I tried, it's not working.
I would appreciate it if you can help me to use blazorsie components to separate digits define thousands.
for example, when I'm entering value 12345678, it shows 12,345,678
thanks in advance
NumericEdit component does not have a GroupSeparator parameter. The GroupSeparator parameter is on the NumericPicker component:
<NumericPicker #bind-Value="#paymentDocumentCreateCommand.TotalPrice" GroupSeparator="," />
NumericPicker was added in Blazorise version 1.0.0.
NumericPicker vs NumericEdit
Workaround:
You can use the TextEdit component and apply a format when you convert the number to string.
<TextEdit #bind-Text="#TotalCost" />
<p>#_totalCost</p>
#code {
private double _totalCost = 1234567890;
private string TotalCost
{
get
{
return _totalCost.ToString("#,#");
}
set
{
_totalCost = string.IsNullOrEmpty(value) ? 0 : double.Parse(value);
}
}
}
Custom binding formats
You can create a custom input component that does this conversion internally.

C# formatting TextBox but only displaying

I can't find how to do it.
I would like the number to be displayed three decimal places.
But to be remembered the whole number.
Example: full number: 8658,645851243511447358350.
Only display in TextBox: 8658,646
How should I do it?
The point is that in the program code read number from TextBox was whole: 8658,645851243511447358350.
I apologize if there is this solution somewhere. C# WinForms.
if this helps, you can use the "tag" property to store the full value, i.e.
TextBox.Text = "8658,646"
TextBox.Tag = "8658,645851243511447358350"
I got a workaround and that is to create your own class and that add additional property i.e., FullValue and keep track of both formatted and full value.
public class CustomTextBox:TextBox{
public string FullValue{get;set;}
}
or you can do
public class CustomTextBox:TextBox{
private string _FullValue;
public string FullValue{get=>_FullValue;set{base.Text=value;_FullValue=value;}}
}

DataGridView: How to allow comma and dot as a separators at the same time

I have a DataGridViewTextBoxColumn which is binded to a property. I want to allow user to input numbers no matter what he uses to separate decimals. Also I don't need spaces or commas to separate thousads.
It's simple:
1.908 = 1.908
1,908 = 1.908
And if there is no way to specify format string, can i Replace(",",".") before binding? Or any other way?
Thank you. (Sorry for my English)
Crete another property of String type which will be bounded to that column.
Then set/read value of original property through this
public class YourBindableItem
{
public decimal OriginalValue { get; set; }
public decimal ParsedValue
{
get { return this.OriginalValue.ToString(); }
set
{
string forParse =
value.Replace(",", Globalization.CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
decimal temp = 0;
if(decimal.TryParse(forParse,
out temp,
Globalization.CultureInfo.InvariantCulture) == true)
{
this.OriginalValue = temp;
}
//if value wasn't parsed succesfully, original value will be returned
this.RaiseOnPropertyChanged(nameOf(this.ParsedValue));
}
}
}
The DataGridView already formats according to the regional settings for the current user, at least if you data bind to an object data source and the property is numeric (i.e. not a string).
You can test this by opening Region and Language in Windows and switching between e.g. the English (United States) format and Swedish (Sweden). In the former case, the input 2.718 will parse correctly while in the second 2,718 will. You'll have to run without debugging in VS in order to load fresh settings.
(I would not suggest trying to parse both comma and dot as a decimal separator for the same user, if you're thinking of doing that. That's not the expected behavior for most users and it would lead to bugs if the user should happen to use the thousand separator too.)

Regex to validate price (type of decimal)

I have looked through stackoverflow trying to find a solution to this but with no luck so hence why I have resulted in asking the question..
I have a field on my form which is price, type of decimal this is optional depending on what they have selected from a dropdown, So I cant use the [Required] attribute.
When the form is submitted if they have chosen a value from the dropdown which requires the user to enter a postage price I then need to check this field to make sure its a valid decimal so to do this I have the following
public static bool IsValid(decimal postagePrice)
{
var regex = new Regex(#"^\d+.\d{0,2}$");
return regex.IsMatch(postagePrice);
}
But it complains and says "Argument type decimal is not assignable to parameter type string" which I understand, I also can't use Decimal.TryParse as that expects a string.
How can I resolve this (I'm not in a position to change the type from decimal to string either)
If all you want is to verify that the value has at most two decimal positions, you could use a modulo:
public static bool IsValid(decimal postagePrice)
{
return postagePrice % 0.01m == 0m;
}
Regular expressions work on strings - it's that simple.
So in one way or another you'll need to covert the decimal to a string before using a regex to validate it.

configurable decimal input format in a DataGridView column

I have an app that allows user to input decimal values, like 00.000, 00.00, 0000.0 and so on.
The problem is that different users require different formats, and I'd like to offer a feature to configure this input format to the end users (like an input template or mask).
What do you think is the best approach to get this accomplished?
You can implement a custom IFormatProvider and use the Parse(string, IFormatProvider) Method to define how the decimals are going to be parsed.
See http://msdn.microsoft.com/de-de/library/t7xswkc6.aspx fpr Method description
See http://www.codeproject.com/KB/cs/custstrformat.aspx for a tutorial
/*
why not make your own method that checks the format length and do something like this as a starting point.
lets say the user typed in the following //replace the following with what ever you are checking against a textbox input.
//This is something that I have quickly written up to test the text that I am passing.
*/
tmpStringTest+= FormatNumberWithCommas(100.ToString()) + " ";
tmpStringTest += FormatNumberWithCommas(1000.ToString());
tmpStringTest += FormatNumberWithCommas(10000.ToString());
tmpStringTest += FormatNumberWithCommas(100000.ToString());
tmpStringTest += FormatNumberWithCommas(1000000.ToString());
public static string FormatNumberWithCommas(string inputString)
{
string tempString;
tempString = string.Format("{0:##,###,###}", Convert.ToInt32(inputString));
return tempString;
}

Categories