Michael A
Michael A

Reputation: 9900

SQL query to HTML table for e-mail

I've been using some code very similar to the following to populate a gridview control:

using(SqlDataAdapter sqlDataAdapter = 
    new SqlDataAdapter("SELECT * FROM Table1",
        "Server=.\\SQLEXPRESS; Integrated Security=SSPI; Database=SampleDb"))
{
    using (DataTable dataTable = new DataTable())
    {
        sqlDataAdapter.Fill(dataTable);
        this.dataGridView1.DataSource = dataTable;
    }
}

I now want to take that grid view and sent the results in an e-mail in a html table. I believe I could work through this by using the gridview as a middle man (add results to gridview then draw html table cell by cell) but I was wondering if there's a way to take the results of an SQL query and draw it into a html table ready for e-mailing?

Summary: How can I query a database and have the results returned in such a way that I could draw a HTML table with them?

Upvotes: 1

Views: 4313

Answers (2)

styfle
styfle

Reputation: 24610

No one in answering so I'll give it a shot.

It appears DataTable has a Rows property that is a collection of all the rows in the data table. All you need to do is iterate over the rows and print an html <tr> tag. Then an inner loop can be used for each column using the <td> tag. I have very little experience with C# but it should look something like this:

        emit("<table>\n");
        foreach(DataRow row in dataTable.Rows)
        {
            emit("<tr>");
            foreach(DataColumn column in dataTable.Columns)
            {
                emit("<td>" + row[column] + "</td>");
            }
            emit("</tr>\n"); // add a newline for readability
        }
        emit("</table>\n");

The emit() function can just concatenate a string if you wish and then you can send an email as html with that string as the body.

Upvotes: 3

Gustavo F
Gustavo F

Reputation: 2206

You can render the HTML code from the gridview directly on code-behind using the RenderControl method, and use the StringBuilder output. Example:

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);

Upvotes: 1

Related Questions