DLL库类

时间:2013-07-08 10:20:50

标签: c# nullreferenceexception

    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页面以显示字典调用的任何特定表。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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

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

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