【问题标题】:I get NullReferenceException我得到 NullReferenceException
【发布时间】:2012-05-25 14:54:11
【问题描述】:

填充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;
    }

【问题讨论】:

标签: c# asp.net repeater nullreferenceexception urldecode


【解决方案1】:

在此代码片段中检查 null 之前,您首先将字段转换为字符串 --> Eval("ProductFeature").ToString()

【讨论】:

    【解决方案2】:

    如下检查null

    <%#kill(Server.UrlDecode(Eval("ProductFeature")?? String.Empty))%>
    

    或者你可以改变如下查询

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

    【讨论】:

      猜你喜欢
      • 2010-09-30
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多