views:

82

answers:

3

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" runat="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.

A: 

I fixed it with this statement

string.IsNullOrEmpty(textbox1.Text) ? 0 : Convert.ToDecimal(textbox1.Text);
Nasser Hadjloo
That statement doesn't really *fix* it. In it, you're saying if there's nothing in the textbox, convert it to a decimal. Otherwise, make it 0. See a problem?
Anthony Pegram
@Anthony - Actually I write ithere so thatI had a mistake - Thank you for your consideration. I correct it for new commers.
Nasser Hadjloo
+3  A: 

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

Oak
+6  A: 

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.

Anthony Pegram