簡體   English   中英

如何使用參考數據表asp.net轉換數據表

[英]how to convert a datatable using a reference datatable asp.net

我發現使用參考數據表將數據表轉換為新數據表的困難。 我的問題令人困惑,我不善於解釋事物,所以我畫了一幅畫(見下文)。

我在內存上有兩個數據表,我需要使用第二個映射表創建第三個數據表以供參考。 列名僅作為示例,不能進行硬編碼。

希望可以有人幫幫我。 非常感謝。

在此處輸入圖片說明

這可能不是最優化的代碼,但它似乎可以工作。...基本上,使用映射表的“新列”列中的列名稱創建一個新的DataTable,然后對第一個表中的每一行進行逐步操作。映射表,將“舊列”列的值存儲在“新列”列中

Protected Sub MapData()

    Dim table1 = New DataTable()
    Dim table2 = New DataTable()
    Dim table3 = New DataTable()

    With table1
        .Columns.Add("Fore Name")
        .Columns.Add("Sir Name")
        .Columns.Add("Date of Birth")
        .Columns.Add("Country")

        Dim newRow = .NewRow()
        newRow("Fore Name") = "AA"
        newRow("Sir Name") = "AA"
        newRow("Date of Birth") = "01.01.1999"
        newRow("Country") = "UK"
        .Rows.Add(newRow)
        ' etc
    End With

    With table2
        .Columns.Add("Old Columns")
        .Columns.Add("New Columns")

        Dim newRow = .NewRow()
        newRow("Old Columns") = "Fore Name"
        newRow("New Columns") = "First Name"
        .Rows.Add(newRow)

        newRow = .NewRow()
        newRow("Old Columns") = "Sir Name"
        newRow("New Columns") = "Last Name"
        .Rows.Add(newRow)

        newRow = .NewRow()
        newRow("Old Columns") = "Date of Birth"
        newRow("New Columns") = "DOB"
        .Rows.Add(newRow)
    End With

    For Each rowData As DataRow In table2.Rows
        table3.Columns.Add(rowData("New Columns"))
    Next

    For Each table1Data As DataRow In table1.Rows
        Dim newRow = table3.NewRow()

        For Each rowMap As DataRow In table2.Rows
            newRow(rowMap("New Columns")) = table1Data(rowMap("Old Columns"))
        Next

        table3.Rows.Add(newRow)
    Next

End Sub

試試這個,但這是在C#中,您可以將其轉換為vb

targetTable.Columns["forename"].Caption = "First Name";// Rename the column
targetTable.Columns["SirName"].Caption = "Last Name";// Rename the column
targetTable.Columns["DateofBirth"].Caption = "DOB";// Rename the column
targetTable.Columns["country"].Table.Columns.Remove("country");//this will remove the column

//reorder column in case you need it
// targetTable.Columns["First Name"].SetOrdinal(0);
// targetTable.Columns["Last Name"].SetOrdinal(1);
// targetTable.Columns["DOB"].SetOrdinal(2);

// newtable =targettable.copy();// this will copy everthing to newtable  

讓我知道是否沒有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM