Reputation: 672
In a C# windows forms class I am binding my textboxes like this.
this.textMargin.DataBindings.Add(new Binding("Text", dt, "Margin", true, DataSourceUpdateMode.OnValidation, 0, "P"));
This is fine for displaying the textbox "textMargin" as a percent. But, when I pass the value of the text box to my update statement, I get a string format error even though I am trying to use Decimal.Parse like this:
decimal testconvert = Decimal.Parse(this.textMargin.Text);
The value I am trying to pass is '100%', but it needs to submit back to the database as 1.
What is the secret here?
Thanks
Upvotes: 0
Views: 2947
Reputation: 441
As you can see Decimal.Parse
will not accept non-digit values, but you can use a simple algorithm like below to get rid of non-digits:
public static string RemoveNonDigits(string s)
{
string newS = "";
if (s.Length == 0) return newS;
for (int i = 0; i < s.Length; i++)
{
if (Char.IsDigit(s[i]) || s[i] == '.')
newS += s[i];
else if (!Char.IsDigit(s[i]))
{
newS += "";
}
return newS;
}
Then you can call
Decimal percent = Decimal.Parse(RemoveNonDigits(textMargin.Text.ToString()));
Upvotes: 0
Reputation: 26386
Try
string textMargin = this.textMargin.Text.EndsWith("%") ? this.textMargin.Text.Replace("%","") : this.textMargin.Text;
decimal testconvert = Decimal.Parse(textMargin) / 100;
Upvotes: 4
Reputation: 54532
This should would work for you, using decimal.TryParse to avoid errors and String.Replace to remove your %.
decimal.TryParse(this.textMargin.Text.Replace("%", ""), out testconvert);
testconvert = testconvert / 100;
Upvotes: 2
Reputation: 499012
%
is not a valid part of a decimal and cannot be parsed by Decimal.Parse
.
You will need to clear it out of the string before parsing.
Upvotes: 1