views:

81

answers:

4

Recently converted my ASP.NET project from 1.1 to 3.5. Hooray! Currently developing a form which has a handful of optional fields. Normally, I'd go through in my code, adding tons of if statements, checking for empty field, and setting value to 0 if so. So, I'm wondering if it would be best to instead, declare private, nullable variables for each of these fields, then add these as parameters for my database update? Using MSSQLS 2000, already set the corresponding fields to allow nulls.

To clarify: The web form has fields for dollar amounts. The default value on the inputs is 0, but if the user deletes one of those 0's, leaving the field empty then submits the form, an exception will be thrown at Convert.ToDecimal(MoneyField.Text) in the argument list of the method that submits all this to the database. Is there a cleaner way to do this that I'm missing?

+1  A: 

It seems unusual that you would have that many fields that are truly nullable, but if you need to describe "no value" separately to any magic domain value of (for example) an int, then yes: Nullable<T> may help. Note that you must manually translate from null to DbNull.Value at the data-layer, as null on a SqlParameter means "don't send this parameter", not "send the value null" (if you see the distinction).

Marc Gravell
I don't know if it's _that many_; form has 21 fields, 9 of them are optional, dollar amounts. So, as an argument, I'm trying: Convert.ToDecimal(MoneyField.Text). Now, if nothing was entered into that field, the conversion fails. So I'm trying to find the cleanest way to allow that argument to be null, so I can pass that null onto the database.
lush
Build the required insert fileds on those that were entered. Build a list of fields to insert and forget about hte rest.
astander
I haven't yet dealt with lists, so I'll have to do some reading to see if that's a viable option.
lush
+1  A: 

I think there is mix up between field validation and Nullable Type here...unless of course you have a some type ...say DateTime and want that to be null...which would not be possible unless usage of Nullable Type.

If that is the case then ...yes..Nullable types are the solution.

Shankar Ramachandran
A: 

Yup, sounds like a plan.

You'd have to change a couple of calls though

static class NConv
{
    static T? ToNullable<T>(string str) where T : struct
    {
        return (T?)(string.IsNullOrEmpty(str) ? default(T?) : Convert.ChangeType(str, typeof(T)));
    }

    static void HowTo()
    {
        double? myBonus = NConv.ToNullable<double>(null);
    }
}
Florian Doyon
A: 

Dynamically build your sql based upon the fields supplied.

sparkkkey