tags:

views:

654

answers:

4

Working on a somewhat complex page for configuring customers at work. The setup is that there's a main page, which contains various "panels" for various groups of settings.

In one case, there's an email address field on the main table and an "export" configuration that controls how emails are sent out. I created amain panel that selects the company, and binds to a FormView. The FormView contains a Web User Control that handles the display/configuration of the export details.

The Web User Control Contains a property to define which Config it should be handling, and it gets the value from the FormView using Bind().

Basically the control is used like this:

<syn:ExportInfo ID="eiConfigDetails" ExportInfoID='<%# Bind("ExportInfoID" ) %>' runat="server" />

The property being bound is declared like this in CodeBehind:

public int ExportInfoID
    {
        get
        {
            return Convert.ToInt32(hfID.Value);
        }
        set
        {
            try
            {
                hfID.Value = value.ToString();
            }
            catch(Exception)
            {
                hfID.Value="-1";
            }
        }
    }

Whenever the ExportInfoID is null I get a null reference exception, but the kicker is that it happens BEFORE it actually tries to set the property (or it would be caught in this version.)

Anyone know what's going on or, more importantly, how to fix it?

A: 

It seems like it's because hfID.Value isn't initialized to a value yet so it can't be converted. You may wanna add a null check in your getter or some validation to make sure hfID.Value isn't null and is numeric.

Quintin Robinson
A: 

The Bind can't convert the null value to an int value, to set the ExportInfoID property. That's why it's not getting caught in your code. You can make the property a nullable type (int?) or you can handle the null in the bind logic.

so it would be something like this

bind receives field to get value from
bind uses reflection to get the value
bind attempts to set the ExportInfoID property // boom, error
Darren Kopp
A: 

use the Null Object design pattern on hfID

http://www.cs.oberlin.edu/~jwalker/nullObjPattern/

Christo Fur
A: 

It works with int?. I had tried that earlier, but something else must have been wrong at the time. Or maybe I'm hallucinating...

Thanks!

Telos