问题
The DataView
object doesn't have a Rows
property like DataTable
.
How do I loop through the rows of a DataView?
回答1:
The DataView object itself is used to loop through DataView rows.
DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.
C#
foreach (DataRowView rowView in dataView)
{
DataRow row = rowView.Row;
// Do something //
}
VB.NET
For Each rowView As DataRowView in dataView
Dim row As DataRow = rowView.Row
' Do something '
Next
回答2:
//You can convert DataView to Table. using DataView.ToTable();
foreach (DataRow drGroup in dtGroups.Rows)
{
dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";
if (dtForms.DefaultView.Count > 0)
{
foreach (DataRow drForm in dtForms.DefaultView.ToTable().Rows)
{
drNew = dtNew.NewRow();
drNew["FormId"] = drForm["FormId"];
drNew["FormCaption"] = drForm["FormCaption"];
drNew["GroupName"] = drGroup["GroupName"];
dtNew.Rows.Add(drNew);
}
}
}
// Or You Can Use
// 2.
dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";
DataTable DTFormFilter = dtForms.DefaultView.ToTable();
foreach (DataRow drFormFilter in DTFormFilter.Rows)
{
//Your logic goes here
}
回答3:
I prefer to do it in a more direct fashion. It does not have the Rows but is still has the array of rows.
tblCrm.DefaultView.RowFilter = "customertype = 'new'";
qtytotal = 0;
for (int i = 0; i < tblCrm.DefaultView.Count; i++)
{
result = double.TryParse(tblCrm.DefaultView[i]["qty"].ToString(), out num);
if (result == false) num = 0;
qtytotal = qtytotal + num;
}
labQty.Text = qtytotal.ToString();
回答4:
You can iterate DefaultView
as the following code by Indexer
:
DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow oRow = dt.DefaultView[i].Row;
// Do your stuff with oRow
// ...
}
来源:https://stackoverflow.com/questions/1427840/looping-through-rows-in-a-dataview