C# 循环遍历数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12198131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through a DataTable
提问by SpaceApple
Well. I have a DataTable with multiple columns and multiple rows.
好。我有一个多列多行的数据表。
I want to loop through the DataTable dynamically basically the output should look as follows excluding the braces :
我想动态地循环遍历 DataTable 基本上输出应该如下所示,不包括大括号:
Name (DataColumn)
Tom (DataRow)
Peter (DataRow)
Surname (DataColumn)
Smith (DataRow)
Brown (DataRow)
foreach (DataColumn col in rightsTable.Columns)
{
foreach (DataRow row in rightsTable.Rows)
{
//output
}
}
I typed that out and noticed this would not work. Can someone please advice on a better way of doing this?
我把它打出来,发现这行不通。有人可以就更好的方法提出建议吗?
采纳答案by Candide
foreach (DataColumn col in rightsTable.Columns)
{
foreach (DataRow row in rightsTable.Rows)
{
Console.WriteLine(row[col.ColumnName].ToString());
}
}
回答by oopbase
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
Console.WriteLine(row[col]);
}
回答by Deepak Kothari
If you want to change the contents of each and every cell in a datatable then we need to Create another Datatable and bind it as follows using "Import Row". If we don't create another table it will throw an Exception saying "Collection was Modified".
如果要更改数据表中每个单元格的内容,那么我们需要创建另一个数据表并使用“导入行”将其绑定如下。如果我们不创建另一个表,它会抛出一个异常,说“集合被修改”。
Consider the following code.
考虑以下代码。
//New Datatable created which will have updated cells
DataTable dtUpdated = new DataTable();
//This gives similar schema to the new datatable
dtUpdated = dtReports.Clone();
foreach (DataRow row in dtReports.Rows)
{
for (int i = 0; i < dtReports.Columns.Count; i++)
{
string oldVal = row[i].ToString();
string newVal = "{"+oldVal;
row[i] = newVal;
}
dtUpdated.ImportRow(row);
}
This will have all the cells preceding with Paranthesis({)
这将包含前面带有 Paranthesis({) 的所有单元格
回答by Chikku Jacob
Please try the following code below:
请尝试以下代码:
//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.
using (reader = cmd.ExecuteReader())
{
// Load the Data table object
dataTable.Load(reader);
if (dataTable.Rows.Count > 0)
{
DataColumn col = dataTable.Columns["YourColumnName"];
foreach (DataRow row in dataTable.Rows)
{
strJsonData = row[col].ToString();
}
}
}

