Getting datarow values into a string?

Kevin picture Kevin · Mar 8, 2012 · Viewed 113.6k times · Source

I have a dataset called "results" with several rows of data. I'd like to get this data into a string, but I can't quite figure out how to do it. I'm using the below code:

string output = "";
foreach (DataRow rows in results.Tables[0].Rows)     
{
    output = output + rows.ToString() + "\n";
}

However, I think I'm missing something because this isn't working. Can someone point me in the right direction?

Answer

Khan picture Khan · Mar 8, 2012

You need to specify which column of the datarow you want to pull data from.

Try the following:

        StringBuilder output = new StringBuilder();
        foreach (DataRow rows in results.Tables[0].Rows)
        {
            foreach (DataColumn col in results.Tables[0].Columns)
            {
                output.AppendFormat("{0} ", rows[col]);
            }

            output.AppendLine();
        }