我在使用 DataTable.Merge 方法和防止行重復時遇到了困難。我有多個資料表需要合并為一個,包括需要合并的重復列。
我的資料表如下所示:
PID|140 PID|140 PID|144 PID|142
1 | X 1| 1| 1|X
2 | 2|X 2|X 2|X
3 | 3| 3|X 3|X
當我合并它們時,它會創建重復的行值。
What I get: What I actually want:
PID|140|144|142 PID|140|144|142
1 | X | | 1 | X | | X
2 | | | 2 | X | X | X
3 | | | 3 | | X | X
1 | | |
2 | X | |
3 | | |
1 | | |
2 | | X |
3 | | X |
1 | | | X
2 | | | X
3 | | | X
我正在設定主鍵并在架構選項上使用 addWithKey,但它似乎在合并時忽略了主鍵約束。
'writeTable being the destination of the merges'
Dim primaryKey(1) As DataColumn
primaryKey(1) = writeTable.Columns("PID")
writeTable.PrimaryKey = primaryKey
'...merging from a selected dataview to table'
selected = view.ToTable("Selected", False,"PID","144")
primaryKey(1) = selected.Columns("PID")
selected.PrimaryKey = primaryKey
writeTable.Merge(selected, False, MissingSchemaAction.AddWithKey)
uj5u.com熱心網友回復:
合并旨在使用資料庫中的更改更新資料表。當您將 writeTable 與 selected 的第二個引數合并為 False 時,您會從 selected, 1,Nothing 2,X 3,Nothing 中獲得新值。每個值都不同于初始值,因此初始值會被覆寫。當第二個引數為 True 時,你得到 1,X 2,Nothing 3,Nothing。保留初始值。如果您想讓 1 和 2 在 140 列中同時顯示 X,則必須過濾所選表以排除 140 列中的空值。然后只有 selected 中的非空值將覆寫初始值。我是這樣做的
Dim NonNullselected = selected.Select($"[140] Is Not Null").CopyToDataTable
140左右的括號是必要的。必須處理以數字開頭的欄位。
我相信您的主要問題是分配主鍵。
Dim primaryKey(1) As DataColumn
這將創建一個包含 2 個元素、索引 0 和 1 的 DataColumn 陣列。
primaryKey(1) = writeTable.Columns("PID")
這將向陣列的第二個元素添加一列。第一個元素是Nothing。
writeTable.PrimaryKey = primaryKey
我可以看到這如何未能成功創建 PK。
我是這樣做的
dt.PrimaryKey = {dt.Columns(0)}
對于您的代碼
writeTable.PrimaryKey = {writeTable.Columns("PID")}
大括號表示陣列是預期的,因此屬性可以處理復合鍵。
Private writeTable As DataTable
Private selected As DataTable
Private Table3 As DataTable
Private Table4 As DataTable
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CreateAndFillTables()
Dim NonNullselected = selected.Select($"[140] Is Not Null").CopyToDataTable
writeTable.Merge(NonNullselected, False, MissingSchemaAction.AddWithKey)
writeTable.Merge(Table3, False, MissingSchemaAction.AddWithKey)
writeTable.Merge(Table4, False, MissingSchemaAction.AddWithKey)
DataGridView1.DataSource = writeTable
End Sub
Private Sub CreateAndFillTables()
writeTable = CreateTable("140")
writeTable.Rows.Add({1, 0})
writeTable.Rows.Add({2})
writeTable.Rows.Add({3})
selected = CreateTable("140")
selected.Rows.Add({1})
selected.Rows.Add({2, 0})
selected.Rows.Add({3})
Table3 = CreateTable("144")
Table3.Rows.Add(1)
Table3.Rows.Add(2, 0)
Table3.Rows.Add(3, 0)
Table4 = CreateTable("142")
Table4.Rows.Add(1, 0)
Table4.Rows.Add(2, 0)
Table4.Rows.Add(3, 0)
End Sub
Private Function CreateTable(SecondColumnName As String) As DataTable
Dim dt As New DataTable
dt.Columns.Add("PID", GetType(Integer))
dt.Columns.Add(SecondColumnName, GetType(Integer))
dt.PrimaryKey = {dt.Columns(0)}
Return dt
End Function
結果

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/378918.html
