Replace string value with '0' when string is empty

夙愿已清 提交于 2019-12-04 23:09:02

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())
Becuzz

You could make a function to keep from copying the code all over the place.

decimal GetTextboxValue(string textboxText)
{
    return Convert.ToDecimal(string.IsNullOrEmpty(textboxText) ? "0" : textboxText);
}

and then use it like this:

GetTextboxValue(txtSample.Text);

You can create an extension method for the string as below

        public static decimal ToDecimal(this string strValue)
        {
            decimal d;
            if (decimal.TryParse(strValue, out d))
                return d;
            return 0;
        }

Then you can just txtSample.Text.ToDecimal() in every place.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!