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

末鹿安然 提交于 2020-01-05 07:13:38

问题


<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.


回答1:


You need to give a stack trace to be sure.

But I can see several issues:

  1. DIV#0 errors inside FormatPercent
  2. 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.




回答2:


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().




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/584570/why-does-my-repeater-keep-crashing-on-evalnull-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!