views:

3194

answers:

8

Hi there,

I'm using Visual Studio 2005 and have a DataTable with two columns and some rows that I want to output to the console. I hoped there would be something like:

DataTable results = MyMethod.GetResults();
Console.WriteLine (results.ToString());

What's the best way (i.e. least amount of coding from me) to convert a simple DataTable to a string?

Thanks, Mark.

A: 

What's wrong with results.ToString()? That converts to a string, doesn't it?

You probably should say what you want the string to look like...

You can iterate over the columns and print their names. You can then iterate the rows and print the value of each column of each row.

John Saunders
ToString() results in the name of the table
Manga Lee
Yeah, I _know_ that, I was hoping the OP would clarify his question to say what output he actually wanted. That didn't work - we still don't actually know what he's looking for.
John Saunders
A: 

very vague ....

id bung it into a dataset simply so that i can output it easily as xml ....

failing that why not iterate through its row and column collections and output them?

John Nicholas
+2  A: 

two for loops, one for rows, another for columns, output dataRow(i).Value. Watch out for nulls and DbNulls.

Petar Repac
+3  A: 

You could use something like this:

Private Sub PrintTableOrView(ByVal table As DataTable, ByVal label As String)
    Dim sw As System.IO.StringWriter
    Dim output As String

    Console.WriteLine(label)

    ' Loop through each row in the table. '
    For Each row As DataRow In table.Rows
        sw = New System.IO.StringWriter
        ' Loop through each column. '
        For Each col As DataColumn In table.Columns
            ' Output the value of each column's data.
            sw.Write(row(col).ToString() & ", ")
        Next
        output = sw.ToString
        ' Trim off the trailing ", ", so the output looks correct. '
        If output.Length > 2 Then
            output = output.Substring(0, output.Length - 2)
        End If
        ' Display the row in the console window. '
        Console.WriteLine(output)
    Next
    Console.WriteLine()
End Sub
Galwegian
BTW, the question is tagged C# ;)
Petar Repac
row(col).ToString() - could you get ReferenceNullException here ?
Petar Repac
+1  A: 

Or, change the app to WinForms, use grid and bind DataTable to grid. If it is a demo/sample app.

Petar Repac
I do not get the whole Console app thing. Didn't DOS die?
MusiGenesis
It's handy for demos when checking some concept or learning things.
Petar Repac
MusiGenesis: I'm not a programmer (can't you tell), I work as a DBA but want to write some programs to help me manage my server estate. I don't have much time and my C# skills are at best novice, and a console app is easier to write than a winforms app.
Mark Allison
+2  A: 
using(var writer = new StringWriter()) {
    results.WriteXml(writer);
    Console.WriteLine(writer.ToString());
}

Of course the usefulness of this depends on how important the formatting is. If it's just a debug dump, I find XML outputs like this very readable. However, if the formatting is important to you, then you have no choice but to write your own method to do it.

Christian Hayter
+2  A: 

I would install PowerShell. It understands .NET objects and has an Format-Table and Export-Csv that would do exactly what you are looking for. If you do any sort of console work it is a great complement/replacement to C# console apps.

When I started using it, I rewrote my console apps as libraries and import the libraries into Powershell. The built-in commandlets make console work so nice.

jwmiller5
A: 
    /// <summary>
    /// Dumps the passed DataSet obj for debugging as list of html tables
    /// </summary>
    /// <param name="msg"> the msg attached </param>
    /// <param name="ds"> the DataSet object passed for Dumping </param>
    /// <returns> the nice looking dump of the DataSet obj in html format</returns>
    public static string DumpHtmlDs(string msg, ref System.Data.DataSet ds)
    {
        StringBuilder objStringBuilder = new StringBuilder();
        objStringBuilder.AppendLine("<html><body>");

        if (ds == null)
        {
            objStringBuilder.AppendLine("Null dataset passed ");
            objStringBuilder.AppendLine("</html></body>");
            WriteIf(objStringBuilder.ToString());
            return objStringBuilder.ToString();
        }

        objStringBuilder.AppendLine("<p>" + msg + " START </p>");
        if (ds != null)
        {
            if (ds.Tables == null)
            {
                objStringBuilder.AppendLine("ds.Tables == null ");
                return objStringBuilder.ToString();
            }


            foreach (System.Data.DataTable dt in ds.Tables)
            {

                if (dt == null)
                {
                    objStringBuilder.AppendLine("ds.Tables == null ");
                    continue;
                }
                objStringBuilder.AppendLine("<table>");

                //objStringBuilder.AppendLine("================= My TableName is  " +
                //dt.TableName + " ========================= START");
                int colNumberInRow = 0;
                objStringBuilder.Append("<tr><th>row number</th>");
                foreach (System.Data.DataColumn dc in dt.Columns)
                {
                    if (dc == null)
                    {
                        objStringBuilder.AppendLine("DataColumn is null ");
                        continue;
                    }


                    objStringBuilder.Append(" <th> |" + colNumberInRow.ToString() + " | ");
                    objStringBuilder.Append(  dc.ColumnName.ToString() + " </th> ");
                    colNumberInRow++;
                } //eof foreach (DataColumn dc in dt.Columns)
                objStringBuilder.Append("</tr>");

                int rowNum = 0;
                foreach (System.Data.DataRow dr in dt.Rows)
                {
                    objStringBuilder.Append("<tr><td> row - | " + rowNum.ToString() + " | </td>");
                    int colNumber = 0;
                    foreach (System.Data.DataColumn dc in dt.Columns)
                    {
                        objStringBuilder.Append(" <td> |" + colNumber + "|" );
                        objStringBuilder.Append(dr[dc].ToString() + "  </td>");
                        colNumber++;
                    } //eof foreach (DataColumn dc in dt.Columns)
                    rowNum++;
                    objStringBuilder.AppendLine(" </tr>");
                }   //eof foreach (DataRow dr in dt.Rows)

                objStringBuilder.AppendLine("</table>");
                objStringBuilder.AppendLine("<p>" + msg + " END </p>");
            }   //eof foreach (DataTable dt in ds.Tables)

        } //eof if ds !=null 
        else
        {

            objStringBuilder.AppendLine("NULL DataSet object passed for debugging !!!");
        }
        return objStringBuilder.ToString();

    } 
YordanGeorgiev