Melt
Melt

Reputation: 501

Asp.Net Class - problem returning html string value

I'm trying to get my class to return a html string which I then assign to a control on a aspx page as: this.div1.InnerHtml = class.News();

However, my catch code is always firing, returning my 'NoValue' message.

The code works fine outside of the class.

When I comment out the reader lines htmlStr.Append(reader["Title"].ToString()); I can get the string back to my calling code, is there something else I need to do, to use readers in classes?

namespace confonline {

public class conf
{
    private string connectionStringBMP = WebConfigurationManager.ConnectionStrings["ConfBMP"].ConnectionString;

    public string News()
    {

        SqlConnection conn = new SqlConnection(connectionStringBMP);
        SqlCommand cmd = new SqlCommand("spNews ", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@number",2);

        SqlDataReader reader;

        try
        {
            conn.Open();

            reader = cmd.ExecuteReader();
            StringBuilder htmlStr = new StringBuilder("");

            while (reader.Read())
            {
               htmlStr.Append("<div class='news'>");
                htmlStr.Append("<img align='left' title='" + reader["ThumbnailText"].ToString() + "' alt='" + reader["ThumbnailText"].ToString() + "' src='images/news/thumbnails/" + reader["PublishYear"].ToString() + "/" + reader["Photo"].ToString() + "'>");
                htmlStr.Append("<a href=news.aspx?p=" + reader["ID"] + ">");
                htmlStr.Append(reader["Title"].ToString());
                htmlStr.Append("</a>");
                htmlStr.Append("</div>");
            }

             string htmlString = htmlStr.ToString();

             reader.Close();

             return htmlString;

        }
        catch (Exception err)
        {
            HttpContext.Current.Response.Write(err.Message);
            string noVal = "No Value";
            return noVal;

        }
        finally
        {
            conn.Close();
        }

    }
}

}

Upvotes: 2

Views: 481

Answers (2)

&#181;Bio
&#181;Bio

Reputation: 10748

if it works when you comment out

 htmlStr.Append(reader["Title"].ToString());

as you say, then there is an exception on that line. Maybe "Title" isn't a valid column? or is sometimes null?

Upvotes: 1

Li0liQ
Li0liQ

Reputation: 11264

Look closer at the Exception you get. reader["Title"] can be null.

Upvotes: 3

Related Questions