Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string value with '0' when string is empty

I'm taking a value from a textbox and converting it to decimal. But, the textbox value could be empty. So, how could I handle empty strings from the textbox?

Unfortunately I have around 50 textboxes to deal with, so answers like 'check for null with IF condition' won't help me. My code will look ugly if I use all those IF conditions.

I have this

Convert.ToDecimal(txtSample.Text)

To handle nulls, I did this

Convert.ToDecimal(txtSample.Text = string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)

But, the above code is displaying '0' in the textbox. User does not want to see '0'. Another solution is to take text box value into a variable and convert the variable like below.

string variable = txtSample.Text;
Convert.ToDecimal(variable = string.IsNullOrEmpty(variable) ? "0" : variable)

But again, I do not want to define around 50 variables. I am looking for some piece of code that handles null values during conversion without adding the extra line of code.

like image 400
ARB Avatar asked Jun 19 '14 14:06

ARB


People also ask

How do you replace occurrences with an empty string?

String.Replace Method (String, String)Use String. Empty or null instead of "" since "" will create an object in the memory for each occurrences while others will reuse the same object.

Is an empty string 0?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

Is nil the same as empty string?

nil is not empty, it is a nil value.

Is an empty string a valid string?

The empty string is a legitimate string, upon which most string operations should work. Some languages treat some or all of the following in similar ways: empty strings, null references, the integer 0, the floating point number 0, the Boolean value false, the ASCII character NUL, or other such values.


1 Answers

But, the above code is displaying '0' in the textbox. User does not want to see '0'.

This is because your statement is assigning the new value to txtSample.Text (when you do txtSample.Text = ...). Just remove the assignment:

Convert.ToDecimal(string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)

To make things easier if you have many text fields to handle, you can define an extension method :

public static string ZeroIfEmpty(this string s)
{
    return string.IsNullOrEmpty(s) ? "0" : s;
}

And use it like this:

Convert.ToDecimal(txtSample.Text.ZeroIfEmpty())
like image 138
Thomas Levesque Avatar answered Oct 30 '22 02:10

Thomas Levesque