开发者

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 databas开发者_StackOverflowe FieldName is null.

Please guide me....


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


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜