简体   繁体   English

遍历asp.net数据表中的行时无数据

[英]No data when looping through rows in an asp.net datatable

When my application loops through the first code block below, I get valid data for all datarow fields. 当我的应用程序遍历下面的第一个代码块时,我将获得所有datarow字段的有效数据。

    For Each dRow In dtExportAddr.Rows
        dtExportAddr.Rows.Add(dRow("MgrID"), dRow("LocationNum"), dRow("DeptNum"), dRow("AddressLinkID"), dRow("PositionID"))
    Next  

But I get an error when looping through that code block "Collection was modified; enumeration operation might not execute." 但是在遍历该代码块“收集已被修改;枚举操作可能无法执行”时出现错误

So I am using the code block below: 所以我正在使用下面的代码块:

        Dim rowCount As Integer = dtExportAddr.Rows.Count
        Dim index As Integer = 0
        For index = 0 To rowCount - 1
            Dim dRow As DataRow = dtExportAddr.Rows.Item(index)
            dtExportAddr.Rows.Add(dRow("MgrID"), dRow("LocationNum"), dRow("DeptNum"), dRow("AddressLinkID"), dRow("PositionID"))
        Next

However, in the second code block, I get a valid record for MgrID, but I get a blank value for the other fields. 但是,在第二个代码块中,我获得了一个有效的MgrID记录,但对于其他字段却获得了空白值。
When I look in the database, all fields in that table have valid values. 当我查看数据库时,该表中的所有字段都具有有效值。

What would be causing the blank values? 什么会导致空白值?

not sure what you are trying to achive as u are selcing count from dtExportAddr and adding records back into it 不知道您要达到什么,因为您从dtExportAddr选择计数并将记录添加回去

Try This - Not tested 试试看-未测试

Dim dRow As DataRow = dtExportAddr.Rows(index) Dim dRow为DataRow = dtExportAddr.Rows(index)

You are still adding rows to the same datatable as you were in the first code block, you are just enumerating through it in a different manner. 您仍然将行添加到与第一个代码块相同的数据表中,只是以不同的方式枚举它。 You should create a new datatable to add your rows to, instead of the one you are looping through. 您应该创建一个新的数据表以将行添加到其中,而不是要遍历的行。

If you do that, you should be able to use either method for your loop. 如果这样做,则应该能够对循环使用任何一种方法。

    Dim tempTable As New DataTable

    For Each dRow As DataRow In dtExportAddr.Rows
        Dim tempRow As DataRow = tempTable.NewRow(dRow("MgrID"), dRow("LocationNum"), dRow("DeptNum"), dRow("AddressLinkID"), dRow("PositionID"))
        tempTable.Rows.Add(tempRow)
    Next

I am not sure that gets you nearer your goal, but I am having some trouble figuring out exactly what you are trying to accomplish when you loop through that data table. 我不确定是否可以使您更接近目标,但是在遍历该数据表时很难弄清楚您要完成的目标。

Your blank values could be caused by the column names being slightly different to how you have typed them? 您的空白值可能是由于列名与您键入它们的方式有些不同?

Im a bit confused about what you are doing too since you seem to be basically duplicating the rows? 我对自己的工作也有些困惑,因为您似乎基本上是在复制行? im not really sure how this relates to writing them out to an excel file 我不太确定这与将它们写到excel文件有什么关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM