user240141
user240141

Reputation:

How do I handle null values in Linq2Sql list

I have few fields in my list in which some fields are coming null as they dont have records in underlying table. So while binding it with repeater control i am getting NullReferenceException.

So, what should i do, handle null while binding or is there any other approach, so that repeater or datalist or gridview will handle the null value automatically.

Note: I am using <%# Eval("FieldName")%> in my aspx page and from database FieldName is null.

Please guide me....

Upvotes: 1

Views: 284

Answers (3)

Andras Zoltan
Andras Zoltan

Reputation: 42353

I've changed this answer since first adding - but it incorporates both parts of my original answer in a more compact form. This handles both a discreet null and DBNull.Value.

<%# (Eval("FieldName") ?? DBNull.Value) != DBNull.Value ? 
     Eval("FieldName") : "" %>

It's a little bit inefficient due to the double-invoke of Eval - you could get around this by adding a helper method to the base class of your control.

I don't recommend modifying the class property code, unless the class is purely for display only, because you'd be changing the semantics of the property get when the value is null.

If the field actually shouldn't be null, then you should have gates on the class and database that prevent nulls occurring.

Upvotes: 1

Robin Maben
Robin Maben

Reputation: 23054

<%# Eval("FieldName") ?? "" %>

Upvotes: 2

user604613
user604613

Reputation:

You could add some calculated properties to your entity class.

Like so:

public string DisplayName
{
     get
     {
         return this.Name ?? "N/A";
     }
}

This will return either the Name or a predefined string, if the Name is null.

Upvotes: 1

Related Questions