How To Convert Empty String To Decimal Value? [Resolved]

Posted by Kasani007 under C# on 10/21/2015 | Points: 10 | Views : 15217 | Status : [Member] | Replies : 4
How To Convert Empty String To Decimal Value?
For Example:
decimal dValue = Convert.ToDecimal(textBox1.Text);

If The TextBox Is Empty(i.e. textBox1.Text="") Then It Is Showing The Exception "FormatException Was Caught" "Input String Was Not In A Correct Format".




Responses

Posted by: Kasani007 on: 10/21/2015 [Member] Starter | Points: 25

Up
0
Down

Resolved
A Simple Method To Convert The Empty String To Decimal Value By Using Ternary Operator i.e., If String Or TextBox Is "" (empty) Then The Variable Takes '0' Else It Converts The TextBox Number String To Decimal Value


decimal deciValue=textBox1.Text == "" ? 0 : Convert.ToDecimal(textBox1.Text);

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 10/23/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
 decimal deciValue = String.IsNullOrEmpty(textBox1.Text)?0M: Convert.ToDecimal(textBox1.Text);


--
Thanks & Regards,
RNA Team

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 10/24/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
decimal deciValue = String.IsNullOrEmpty(textBox1.Text) ? default(decimal) : Convert.ToDecimal(textBox1.Text);




--
Thanks & Regards,
RNA Team

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 10/24/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
0
Down
decimal number;

decimal deciValue = Decimal.TryParse(textBox1.Text, out number) ? number : 0M;


--
Thanks & Regards,
RNA Team

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response