简体   繁体   中英

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.

    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.
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

Try This - Not tested

Dim dRow As 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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