Getting datarow values into a string?

大城市里の小女人 提交于 2020-01-01 01:12:11

问题


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?


回答1:


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();
        }



回答2:


I've done this a lot myself. If you just need a comma separated list for all of row values you can do this:

StringBuilder sb = new StringBuilder();
foreach (DataRow row in results.Tables[0].Rows)     
{
    sb.AppendLine(string.Join(",", row.ItemArray));
}

A StringBuilder is the preferred method as string concatenation is significantly slower for large amounts of data.




回答3:


You can get a columns value by doing this

 rows["ColumnName"]

You will also have to cast to the appropriate type.

 output += (string)rows["ColumnName"]



回答4:


Your rows object holds an Item attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString() on the row. You should access each column from the row separately, use a for or a foreach to walk the array of columns.

Here, take a look at the class:

http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx



来源:https://stackoverflow.com/questions/9620434/getting-datarow-values-into-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!