使用datagrid Row Added Event在表中添加行时发生主键冲突错误

时间:2014-07-09 13:57:11

标签: vb.net

我在以下代码中遇到主键错误:

Private Sub ProductForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'TODO: This line of code loads data into the 'BismillahDBDataSet.Product' table. You can move, or remove it, as needed.
    Me.ProductTableAdapter.Fill(Me.BismillahDBDataSet.Product)

    AddHandler ProductGrid.RowsAdded, AddressOf ProductGrid_RowsAdded

    Dim ProductAdapter = New SqlDataAdapter("Select * from product", My.Settings.BismillahDBCN)
    Dim ProductTable = New DataTable()
    ProductAdapter.Fill(ProductTable)
    ProductGrid.DataSource = ProductTable

End Sub

Private Sub ProductGrid_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs)
    Dim RowID As Integer = ProductGrid.CurrentRow.Index
    Dim ColID As Integer = ProductGrid.CurrentCell.ColumnIndex

    Try
        SQLText("insert into Product (ProductID, ProductName,UnitPrice,QtyInHand) values('" & ProductGrid.Item(0, RowID).Value & "','" & ProductGrid.Item(1, RowID).Value & "','" & ProductGrid.Item(2, RowID).Value & "','" & ProductGrid.Item(3, RowID).Value & "')")

    Catch ex As Exception
        Exit Sub
    Finally
        '           Dim RowID As Integer = ProductGrid.CurrentRow.Index
        '          Dim ColID As Integer = ProductGrid.CurrentCell.ColumnIndex

        Dim cn As New SqlConnection(My.Settings.BismillahDBCN)
        cn.Open()
        Dim cmd As New SqlCommand
        cmd.Connection = cn
        Dim rdr As SqlDataReader

        cmd.CommandText = "Select * from Product where Productid=" & ProductGrid.Item(0, ColID).Value
        rdr = cmd.ExecuteReader
        rdr.Read()                  'while rdr.Read()
        If rdr.HasRows = True Then
            MsgBox("Productid already exists!, Enter new ProductID")
            'TxtInvoiceNo.Focus()
            '                Exit Sub
        End If

    End Try
End Sub

我也尝试了UserAddedRows事件,但是当我开始输入PRODUCTGRID的PRODUCTID列(甚至1位数)时,它会显示消息消息

请帮忙

0 个答案:

没有答案