I get NullReferenceException

本文关键字:NullReferenceException get | 更新日期: 2023-09-27 18:35:17

我在填充 Repeater 时得到 NullReferenceException。某些产品具有空。我在使用 UrlDecode() 和 kill() 方法时使用了 IsNullControl() 方法以避免异常。但我仍然有错误。

   <asp:Repeater ID="rptProducts" runat="server">
        <ItemTemplate>
                <div>
                    <%# Eval("ProductName")%>
                </div>
                <div>
                    <%# kill(Server.UrlDecode(IsNullControl(Eval("ProductFeature").ToString())))%>
                </div>
        </ItemTemplate>
    </asp:Repeater>
    try
    {
        ProductsDataContext pdc = new ProductsDataContext();
        var query = from p in pdc.Products
                    select p;
        rptProducts.DataSource = query;
        rptProducts.DataBind();
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    public static string kill(string val)
    {
        val = val.Replace("<ul>", " ");
        val = val.Replace("<li>", " ");
        val = val.Replace("</li>", "<br/>");
        val = val.Replace("</ul>", " ");
        return val.ToString();
    }
    public static string IsNullControl(string val)
    {
        string space = " ";
        if (string.IsNullOrEmpty(val))
        {
            val = space;
        }
        return space;
    }

I get NullReferenceException

您先将字段转换为字符串,然后再检查此代码片段中的 null --> Eval("ProductFeature").ToString()

检查空

值,如下所示
<%#kill(Server.UrlDecode(Eval("ProductFeature")?? String.Empty))%>

或者您可以按如下方式更改查询

 var query = from p in pdc.Products
             select p
             where p!= null;