开发者

How to use ? keyword for string

I have a simple condition and want to implement it with ?: keyword but compiler do't let me. this is the exact sample

// in asp page decleration
<ajaxtoolkit:FilteredTextBoxExtender id="ftbeNumeric" runat="server" TargetControlID="textbox1" FilterType="Numbers" />
<asp:TextBox ID="textbox1" run开发者_如何学编程at="server" />

// in code behind 
decimal x = textbox1.Text != string.IsNullOrEmpty ? Convert.ToDecimal(textbox1.Text) : 0;

I also try this

// in code behind 
decimal x = Convert.ToDecimal(textbox1.Text) != 0 ? Convert.ToDecimal(textbox1.Text) : 0;

bith of these sample face with error.

how to define this with ?: keyword? and note that textbox.text` may be null.


Consider changing it to something like

decimal x;
if (!decimal.TryParse(textbox1.Text, out x))
{
    // throw an exception?
    // set it to some default value?
}

Of course, if you would like to throw an exception on an invalid/missing input, you could simply use the .Parse method instead and it would throw one for you. But using .TryParse would allow you to customize the exception's message or simply handle it another way, such as reprompting the user.


String.IsNullOrEmpty is a method, not a field. So proper usage is String.IsNullOrEmpty(textbox1.Text).


I fixed it with this statement

string.IsNullOrEmpty(textbox1.Text) ? 0 : Convert.ToDecimal(textbox1.Text);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜