I am trying to create a save Button and it includes 2 values in TextBox controls that are considered currency in sql. They are decimal in the TextBox. How do I pass the value? I tried this to no avail:
decimal taxOpen = Convert.ToDecimal(taxOpenTextBox).Text;
Any help on the correct syntax would be great.
You need to access the Text property. You also should use TryParse, which returns false instead of throwing an exception if the parse fails:
decimal value;
if(!decimal.TryParse(taxOpenTextBox.Text,
NumberStyles.Currency,
NumberFormatInfo.InvariantInfo,
out value))
MessageBox.Show("Please enter a valid number");
The needed things are found in System.Globalization.
You need to get the value of the taxOpenTextBox, not the box itself.
Related
I am using below Property example to make some calculation on textbox and if textbox is null I am assigning zero to it so calculation won't fail as you can see I am using Math.Round and I want to make several checks on these textbox input like
textbox that only accepts numbers I searched and found method 1
I want my textbox to be formated I searched and found Method 2
Now my question is ..
Is there any way to mareg all these method in the property method I am using
so my code won't be like "spaghetti code" ?
is there any better ways to do these checks ?
Thank you in advance
Property example
public double ItemPriceResult
{
get
{
return Math.Round(ItemCost * RevenuePercentage / 100 + ItemCost, 0);
}
}
Method 1
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
Method 2
textBox1.Text = string.Format(System.Globalization.CultureInfo.GetCultureInfo("id-ID"), "{0:#,##0.00}", double.Parse(textBox1.Text));
UPDATE after some answers
MaskedTextBox seems fit my needs I read and searched and below some question
if you kindly would like to help me
I need to use MaskedTextBox because I can set it to accept
number and I can also force number formating so
also I need to make number textboxs easer to read for users
so 1000 will be come 1,000
and 10000 will be come 10,000
then according to Microsoft Docs formating MaskedTextBox to fit my needs
Masked MaskedTextBox with 999,999,999,
second I do not want the PromptCharto be visible I google it but none of search result did it
Try this , it will accept only numbers and u can format the string as u want using regex.
public static string ToMaskedString(this String value)
{
var pattern = "^(/d{2})(/d{3})(/d*)$";
var regExp = new Regex(pattern);
return regExp.Replace(value, "$1-$2-$3");
}
You have a TextBox. Alas you don't tell what kind of TextBox you use. System.Windows.Forms.TextBox? System.Web.UI.MobileControls.TextBox?
You write "if text box is null I am assigning zero to it". I assume that you mean that if no text is entered in the text box you assume that 0 is entered.
Furthermore you want to format the output of the text box whenever the text is changed. So while the operator is typing text you want to change this text? For the operator this is very annoying.
Wouldn't you prefer that the operator is obliged to type his text in the format you desire, helping him visually. For this you may use the class MaskedTextBox
The MaskedTextBox has a property Mask, which forces the operator to type in a certain format. I'm not really familiar with what you do with the format {0:#,##0.00}, but I assume you want the output double in a real format with two digits after the decimal point using the decimal point and the thousand separator as common in the current culture.
via the designer put in initialize component:
this.maskedTextBox1.Mask = "99990.00";
after adding the event for text changed:
private void maskedtextBox1_TextChanged(object sender, EventArgs e)
{
double enteredValue = 0.0; // value to use when empty text box
if (!String.IsNullOrEmpty(this.maskedtextBox1.Text))
{
enteredValue = double.Parse(maskedTextBox1.Text, myFormatProvider)
}
ProcessEnteredValue(enteredValue);
}
}
After your edit, the specifications have changed.
While entering the number in the text box, the operator should not have any visual feedback of the formatting of his number.
The operator is free to enter the real number in any commonly used format.
The value of the text box should not be used while the operator is editing the text box.
Only after editing is finished, the value of the text box should be interpreted for correctness, and if correct it should be used.
The actually used value should be displayed in the text box in a defined format.
The desire not to show any visual feedback while entering is understandable. After all, the program doesn't care whether the operator types 1000, 1000.00, or even 1.0E3.
The MaskedTextBox is especially used to force the operator to enter his number in a given format. Since this is not desired, my advise would be to use a TextBox instead of aMaskedTextBox.
However, because you give the operator the freedom to enter his number in any way he wants, including copy-paste, repairing typing errors, etc. you'll have to add the possibility for the user to express to the program that he has finished entering the number.
An often used method in the windows UI would be a Button. Another possibility would be the enter button. Be aware though that this is not really standard within windows. It might make learning your program a little bit more difficult.
So after the operator notified that he finished editing and the corresponding event function is called, your code could be:
// Get the numberformat to use, use current culture, or your own format
private readonly IFormatProvider myNumberFormat = CultureInfo.CurrentCulture.NumberFormat
private void OperatorFinishedEditing(TextBox box)
{
// read the text and try to parse it to a double
// accepting all common formats of real numbers in the current culture
bool valueOk = true;
double resultValue = 0;
if (!String.IsNullOrEmpty(box.Text))
{
bool valueOk = Double.TryParse(box.Text, out resultValue);
}
if (valueOk)
{
box.Text = FormatResultValue(resultValue);
ProcessValue(resultValue);
}
else
{
ShowInputProblem();
}
}
I'm not sure exactly how to write the title for this question, let me dive into it to make it clear...
I have a textbox in a WPF application. This textbox has two way binding to a property in the class - an integer. This integer represents a currency amount multiplied by 100 - e.g. $100.00 --> 10000 in integer value.
I'm looking for a format that might allow the user to enter the value of the amount into the textbox with decimals and have that value wind up stored as the integer in the way I've described above. It should also display any value with the decimal added in the appropriate position.
e.g. user enters $22.31 and integer becomes 2231, value 54598 becomes $545.98 when displayed to the user.
Any ideas on how I can set this up? What I have right now in the binding is the currency string format, but that isn't quite doing it for me.
<TextBox
Name"TotalAmountLabel"
Text="Binding Path=TotalAmount, StringFormat=C, Mode=TwoWay}" />
And the underlying property:
Private _TotalAmount As Integer
Public Property TotalAmount() As Integer
Get
Return _TotalAmount
End Get
Set(ByVal value As Integer)
_TotalApprovalAmount = value
End Set
End Property
Any ideas? I know I might have done a lousy job explaining what I'm looking for, so if something is unclear, please ask and I'll clarify.
The typical way to handle this would be to use an IValueConverter, not a string format binding.
This would let you convert to and from text in any format you choose, but store the data in an integer.
You have tagged both C# and VB, my solution is a C# solution. Assuming the user can only go up to 2 demcimal points:
String toInteger = Regex.Replace(TextBox.Text,"[$]|[.]","");
// You can cast the toInteher to int value if you want like:
// Convert.ToInt32(toInteger);
String toValue = "$" + toInteger.Substring(0, toInteger.Lenght-2) + "." + toInteger.Substring(toInteger.Lenght-2, 2);
I am getting the error "System.FormatException : input string was not correct".
TextBox2.Text = objnm.rupees(Convert.ToInt64(Convert.ToDecimal(txtWOrds.Text.Trim())));
First, you don't need to convert it to decimal (Convert.ToDecimal) and then to Int64 (Convert.ToIn64).
Second, if txtWOrds.Text is not a number or is empty, than you will get this exception. Make sure that it is a number.
Third, if your value is a number, than your problem likes somewhere in objnm.rupees()
You should check the input in case its empty, like string.IsNullOrEmpty(txtWOrds.Text) then proceed with the parsing of the contents of the textbox.
Also you should be using TryParse which evaluates if the text can be parsed and if true you can use the value of the out parameter of this method.
In your case it could fail if the TextBox is empty.
Also if its anything related to money/currency not sure if you need the conversion to Long (seems like a mismatch there, please clarify. If you want a specific set of decimal points then it would be better to use decimal.Round )
Decimal value = default(decimal);
bool isValid = decimal.TryParse(txtWOrds.Text.Trim(), out value);
if (isValid)
{
//your code using output 'value'
}
Remove Convert.Int64 and just use Convert.ToDecimal (ideally you should use decimal.TryParse). Also, ensure that the input textbox contains the correct type (a decimal)
I dont know what is the maximum and minimum value of string in RangeValidator in asp.net
is anyone have idea?
in such interview of asp.net company ask this question? so i want to know please help me out
thnx in advance
The RangeValidator control is used
to check that the user enters an input
value that falls between two values.
It is possible to check ranges within
numbers, dates, and characters.
Note:
1.The validation will not fail if the input control is empty. Use the
RequiredFieldValidator control to make
the field required.
2.The validation will not fail if the input value cannot be converted to the
data type specified. Use the
CompareValidator control, with its
Operator property set to
ValidationCompareOperator.DataTypeCheck,
to verify the data type of the input
value.
3.Specifies the data type of the value to check. The types are:
Currency Date Double Integer String
4.The RangeValidator control throws an exception if the value specified by
the MaximumValue or MinimumValue
property cannot be converted to the
data type specified by the Type
property.
source :
http://forums.asp.net/t/1046041.aspx/1?how+to+use+RangeValidator+for+String+type+
this may be simple but im still new to this language.
I'm creating a windows application where is a text box and a a button. What it will do is take the value entered in the text box and create a .txt file with the value entered in the textbox as its content.
I've don this. I have successfully add "5" to the textbox and pressed the button and it will create a txt file with content "5" in it.
My question is, how do I format the value form the text box to something like this xxxxxxx.xxxxx?
So if I enter 5 how do I make it create in text to become 0000005.00000?
Or if I enter 5.4 how do i make it become like this 0000005.40000?
Can anyone shed a light? Or coding sample?
What you have to do is to parse the string from the TextBox into a double and then format it back to string using NumberFormatInfo.
To parse the string, use:
Double d;
Double.TryParse("5.4", out d);
To format to what you want, have a look at these docs and choose the format that you need: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
Parse your TextBox text into a double variable (using double.Parse or double.TryParse) and try something like this:
double d = 5.0d;
Console.WriteLine(string.Format("{0:0000000.00000}",d));
d = 5.4d;
Console.WriteLine(string.Format("{0:0000000.00000}",d));
Try the following:
int number = 5;
string content = number.ToString("0000000.00000");
This blog post is good for how to use string.Format - http://blog.stevex.net/string-formatting-in-csharp/
Also MSDN is very helpful - http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
For example, "if using i enter 5.4 and how do i make it become like this 0000005.40000?":
Take a look at that MSDN link, under heading "The Decimal ("D") Format Specifier":
Console.WriteLine(value.ToString("D8"));
// Displays -00012345
Take a look at that MSDN link, under heading "The Fixed-Point ("F") Format Specifier"
integerNumber = -29541;
Console.WriteLine(integerNumber.ToString("F3",
CultureInfo.InvariantCulture));
// Displays -29541.000
But actually, to achieve what you're looking for then you are probably best using a format string like:
var f = 5.4;
f.ToString("000000000.0000000000000");
// Displays 000000005.4000000000000
First of all, a text box gives you the value as a (text) string. If you want to process it further as a number (which you do), you first need to convert (parse) it. Then, you just format the number the way you want:
var number = Decimal.Parse(textBox.Text);
writer.Write(number.ToString("{0:0000000.00000}", number));
Look up string.Format():
http://alexonasp.net/samples/stringformatting/