【问题标题】:DLL Library classDLL 库类
【发布时间】:2013-07-08 10:20:49
【问题描述】:
    public string getReportHTML(_TableProperty tableProperty, Stream stream)
    {
        string sql = "select ";
        string columnAdd="<table><tr><td>";

        foreach (var column in tableProperty.Columns)//nullreferencepointexception
        {

            sql += column.Key + " as [" + column.Value + "],";
            columnAdd += "<th> column.Value </th>";

        }
        columnAdd += "</table></tr></td>";
        sql=sql.TrimEnd(',');
        sql += " from" + tableProperty.ReportTable;
        sql = sql + " where 1=1 " + (string.IsNullOrEmpty(tableProperty.ReportCondition) ? "" : "and " + tableProperty.ReportCondition);

        SqlConnection _con = new SqlConnection(@"server=mausam-pc\sqlexpress;uid=***;pwd=***;initial catalog=HRMSN");
        SqlCommand _cmd = new SqlCommand(sql, _con);
        _con.Open();
        SqlDataReader _reader = _cmd.ExecuteReader();


        while (_reader.Read())
        {
            foreach (var column in tableProperty.Columns)
            {
                columnAdd += _reader.GetOrdinal(column.Value);
            }
        }
        columnAdd += "</table></tr></td>";
        string htmlread = "<html><title>General</title><body> columnAdd </body></html>";

        if (_reader != null)
        {
            _reader.Close();
        }
        _con.Close();
        return htmlread;

    }

请告诉我如何删除空点异常或如何在列的情况下为 foreach 循环使用 new 关键字。它是一个 dll 库类,用于呈现 HTML 页面,以显示字典调用的任何特定表。

【问题讨论】:

  • 很明显,填充_TableProperty 类的任何内容都没有填充Columns 属性,这超出了您发布的代码的范围。 “foreach 循环的新关键字在列的情况下” - 您是否尝试构建 Columns 属性?

标签: c# nullreferenceexception


【解决方案1】:

在 foreach 循环之前检查 tableProperty.Columns 中的空值。

【讨论】:

  • 请返回stackoverflow.com/questions/17553209 并输入答案。您添加到问题中的内容有效。它只需要对正在发生的事情进行一些解释。如果您需要,我会密切关注并提供帮助。
【解决方案2】:

在尝试循环集合之前确保tableProperty 不为空。

if (tableProperty != null) {
  foreach (var column in tableProperty.Columns)
  {
    columnAdd += _reader.GetOrdinal(column.Value);
  }
}

您可能还想考虑使用StringBuilder 而不是连接字符串。

【讨论】:

    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多