ADO.NET中关于主键为自动编号的主从表(主祥表)的修改

VB.net(winform) 专栏收录该内容
20 篇文章 0 订阅

ADO.NET中关于主键为自动编号的主从表(主祥表)的修改

主从表的结构关系统如下:

主表PT:

pt.字段A——自动编号(主键)
pt.字段B——字符
pt.字段C——字符

从表CT:

ct.字段A——自动编号(主键)
ct.字段B——数字(pt.字段A的值)
ct.字段C——字符

 

保存代码:
===================================================

        Me.Validate()
        Try
            If Me.DBDataSet.主表PT.GetChanges IsNot Nothing Then

                '获取主表PT新增加行的数量
                Dim foundRows As DataRow() = Me.DBDataSet.主表PT.Select("", "字段A DESC", DataViewRowState.Added)


                If foundRows.Length > 0 Then
                     Dim command As OleDb.OleDbCommand = Me.主表PTTableAdapter.Connection.CreateCommand()
                    command.CommandText = "SELECT TOP " & foundRows.Length.ToString & "  字段A FROM 主表PT  ORDER BY 字段A DESC"
                    If Me.主表PTTableAdapter.Connection.State = ConnectionState.Closed Then Me.主表PTTableAdapter.Connection.Open()

                    '保存主表PT
                    Me.主表PTTableAdapter.Update(Me.DBDataSet.主表PT)

                    '获取主表PT新增加的行的真正编号,并修改子关系表
                    Dim reader As OleDb.OleDbDataReader = command.ExecuteReader()
                    Dim ParentRowIndex As Integer = 0
                    While reader.Read()
                        Dim childRows() As DataRow
                        Dim relation As DataRelation
                        Dim childRowIndex As Integer
                       '
                       '修改主表PT,使其显示真正的编号
                        foundRows(ParentRowIndex).Item("字段A") = reader.GetInt32(0)
                       
                       '修改 从表CT字段B 与 主表PT字段A 相对应的值
                        For Each relation In Me.DBDataSet.主表PT.ChildRelations
                            childRows = foundRows(ParentRowIndex).GetChildRows(relation)
                            For childRowIndex = 0 To childRows.Length - 1
                                childRows(childRowIndex).Item("字段B") = reader.GetInt32(0)
                            Next childRowIndex
                          Next relation
                        ParentRowIndex = ParentRowIndex + 1
                    End While
                    reader.Close()
                    Me.主表PTTableAdapter.Connection.Close()
                    Me.DBDataSet.主表PT.AcceptChanges()

                Else
                    '保存主表PT
                    Me.主表PTTableAdapter.Update(Me.DBDataSet.主表PT)
                End If
            End If
            '保存 从表CT
            Me.从表CTTableAdapter.Update(Me.DBDataSet.从表CT)
            Me.DBDataSet.从表CT.AcceptChanges()
            MessageBox.Show("保存成功!")
        Catch ex As Exception
            MessageBox.Show("失败原因:" & ex.Message, "保存失败!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try

 

 

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值