How do you handle NULL values in DataBound controls? - asp.net

I am trying to limit the characters displayed in ASP.NET Label controls that have their Text values databound to a SQL Database. If the field in the database is not NULL, I do not have any trouble. If they are NULL, I get the exception "Object reference not set to an instance of an object."
My code is as follows:
<asp:Label ID="LabelDescriptionLabel" runat="server" Text='<%# IIf(Not IsDBNull(Item.LabelDescription), IIf(Item.LabelDescription.ToString.Length > 30, Left(Item.LabelDescription, 30) & "...", Item.LabelDescription), Item.LabelDescription)%>' />
I have also tried the following, without any luck:
<asp:Label ID="LabelDescriptionLabel" runat="server" Text='<%# IIf(Not IsNothing(Item.LabelDescription), IIf(Item.LabelDescription.ToString.Length > 30, Left(Item.LabelDescription, 30) & "...", Item.LabelDescription), Item.LabelDescription)%>' />
I am using ASP.NET with VB.NET. I have tried using the CSS "text-overflow: ellipsis" method as well, but I had some table formatting issues that I have not resolved.
Is there a way to handle these NULL values and prevent run-time exceptions?
Thanks!

One problem you are having is that the old IIF is a function which evaluates all the parts before it decides what to return.
IIF(Not IsDBNull(Item.LabelDescription), TruePart, FalsePart)
It does not matter if the expression is true or not, the TruePart and
FalsePart statements will always be executed. Since they include references to something which may be DBNull/Nothing/null, you get an error.
Something else though is that Nothing is not the same as DBNull, and if Item is an Object which can be Nothing/null, then testing the description of Nothing/null will be problematic.
The If Operator has been available since abut 2008. The structure is the same but it only evaluates the test condition and the True or False expression which applies:
If( Condition, TruePart, FalsePart )
The "short circuiting" prevents the expression/Part which does not apply from being evaluated. As long as the rest of the code is valid, you should be able to just clip one of the Is from the IIF functions.
Since you want to the object Nothing I would use the Nothing keyword rather than the VB IsNothing function:
If(Item IsNot Nothing),
If(Item.LabelDescription.ToString.Length > 30, x, y), y)
The If operator is not the same as the If/Then/Else statement block.

Related

How to determine css's class with if statement

<div class="<%#((int)Eval("Cevaplanma_Sayisi")>0) ? "divcevaplanmasayisiozel" : "divcevaplanmasayisinormal" %>">
my code is above.the code runs when I use access database but it doesnt run with sqlserver2008 where is the error.it says when I runs the code invalid exception handled
Try this:
<div class='<%#(((int)Eval("Cevaplanma_Sayisi"))>0) ? "divcevaplanmasayisiozel" : "divcevaplanmasayisinormal" %>'>
The first problem is that you need to convert the object value of "Cevaplanma_Sayisi" into int.
The second problem is that you must wrap the Eval statement within ' and ', otherwise you get malformed html.

Setting DevExpress ASPxCheckBox CheckState via Eval

In ASP.Net 4.0, I'm trying to utilise the DevExpress ASPxCheckBox's ability to have "three states": checked, unchecked and indeterminate. I'd like to set this based on the value of a boolean: "Checked" when the boolean is true, "Unchecked" when false, and "Indeterminate" when null. To this end, I'm trying to use the following code in my page:
<dx:ASPxCheckBox ID="cb_located" runat="server" AllowGrayed="true" AllowGrayedByClick="true" CheckState='<%# Eval("located") == DBNull.Value ? "Indeterminate" : (bool)Eval("PropertyLocated") == true ? "Checked" : "Unchecked" %>' />
However, this gives me the error
CS0030: Cannot convert type 'string' to
'DevExpress.Web.ASPxClasses.CheckState'
Can anyone help me with the correct syntax please?
You need to use CheckState enumeration. So instead of string value "Indeterminate" use CheckState.Indeterminate etc.

Custom Repeater with hiractial Databinding

Im using a Custom NestedRepeater Control for ASP.NET which can be found on code project
The source is in c# which i have converted to vb and plugged into my solution, so far so good. The problem, im having is databinding to the repeater, my code behind looks like this...
'' get all pages
Dim navPages As DataSet = Navigation.getMenuStructure()
navPages.Relations.Add(navPages.Tables(0).Columns("ID"), navPages.Tables(0).Columns("ParentID"))
NestedRepeaterNavigation.RelationName = RelationName
NestedRepeaterNavigation.DataSource = navPages
NestedRepeaterNavigation.RowFilterTop = "ParentID is null"
NestedRepeaterNavigation.DataBind()
Then in the item template of my custom repeater im trying the following...
<ItemTemplate>
<img src="/pix.gif" height="10" width="<%#(Container.Depth * 10)%>">
<%# (Container.DataItem as DataRow)["DESCRIPTION"]%>
<%# (Container.NbChildren != 0 ? "<small><i>(" + Container.NbChildren.ToString() +")</i></small>" "") %><small><i></i></small>
</ItemTemplate>
The databinding falls over; firstly that 'as DataRow' says it was expecting an ')'. And secondly that '!=' identifier expected.
Is this due to the translation from c#, should the databinding be different?
Though I've not programmed in VB.net for long (about 3 years) but I know that AS is not applicable in VB.net you need ctype to cast Container.DataItem like
CType(Container.DataItem, DataRow).
you can also try DirectCast(Container.DataItem, DataRow) but I don't think this will work.
Also for inequality comparison you can use
Not Container.DataItem = 0
but not !=

using Eval in vb.net

hiii everyone....
i have small problem with my code in vb.net that i want to use (Eval) in my project
so i write this code :
<asp:Label ID="Label1" runat="server"
Text='<%#Eval("PAG_PAGES") == null ? "" : ((PostAgenciesModel.PAG_PAGES)(Eval("PAG_PAGES"))).PAGE_TITLE_AR %>' />
and this code i used in my C# project .... all want to show the (Label1) in inside my GridView....
("PAG_PAGES") is the name of table..
PostAgenciesModel is the edmx...
PAGE_TITLE_AR is the colum in ("PAG_PAGES") that i want to show it
can anyone help plzzz
thanxx
The issue is that you are using C# features in a VB.NET web application.
The null keyword and the ?: and == operators are C# constructs
In VB.NET, null is Nothing, == is IS and ?: is the IIf function.
<%# If(Eval("PAG_PAGES") Is Nothing,
"",
DirectCast(Eval("PAG_PAGES"), PostAgenciesModel.PAG_PAGES).PAGE_TITLE_AR) %>
Elaborating on what Oded wrote:
expr == null ---> expr Is Nothing
a ? b : c ---> If(a, b, c)
(Type)expr ---> DirectCast(expr, Type)

Why does my repeater keep crashing on Eval(NULL) values?

<asp:Repeater ID="rptLessons" runat="server">
<ItemTemplate>
<tr>
<td><%#Eval("fullname")%></td>
<td><%#isCompleted(Eval("totallessons"), Eval("completedlessons"), Eval("totalNumAvail"), Eval("totalNumCorrect"))%></td>
<td><%#FormatPercent(Eval("totalnumcorrect") / Eval("totalNumAvail"))%> <%-- (<%#Eval("totalnumcorrect")%> / <%#Eval("totalNumAvail")%>) --%></td>
<td><%#FormatPercent(Eval("completedlessons") / Eval("totallessons"))%> <%-- (<%#Eval("completedlessons")%> / <%#Eval("totallessons")%>) --%></td>
<td><%#Eval("lastaccessed")%></td>
</tr>
</ItemTemplate>
</asp:Repeater>
I can't figure it out but as soon as it hits some NULL data it refuses to move on to drawing the next elements.
You need to give a stack trace to be sure.
But I can see several issues:
DIV#0 errors inside FormatPercent
NULL errors.
Example Solution
(System.Convert.ToInt32 should convert DBNull/NULL to 0)
Or alter isCompleted to accept Object paramters and do your NULL / DBNull checking inside the function.
On slightly different approach that might be helpful would be to do your computations in your code behind rather than inline in the markup. Just easier to check for nulls etc. I almost always go down this path with anything other than a simple Eval() in my markup.
<td>
<%#GetCorrectPercent()%>
</td>
protected string GetCorrectPercent()
{
if(Eval("totalnumcorrect") == null || Eval("totalNumAvail") == null)
return "n/a";
return ((int)Eval("totalnumcorrect") / (int)Eval("totalNumAvail")).ToString();
}
Not sure all the formatting is correct here but this should get you going in a different direction. Eval() will work within the called methods so long as the caller is current performing a DataBind().
If I had to guess, I would say that your isCompleted function doesn't handle values of Nothing. This is a guess because the function hasn't been listed in your example.
I tend more towards the explicit. Forgive any minor mistakes in the code, I'm not able to test this.
If in your markup you swap out those evals for literals then in the code behind:
If you have a collection of MyClass.
In your page's init event
this.rptLessons.OnItemDataBound += rptLessons_DataBound...
In the load or where ever you choose
this.rptLessons.DataSource = CollectionOfMyClass;
this.rptLessons.DataBind();
Then in that itemDataBoundEvent
MyClass myClass = (MyClass)ri.DataItem;
Literal litFullname = FindControl(ri, "litFullName");
litFullName.Text = myClass.Fullname;
This way you can cater for nulls etc in a more controlled way than using eval.

Resources