VB.NET数据集更新

时间:2009-11-08 06:45:56

标签: vb.net dataset

为什么我的代码集没有在DataSet中更新?然后它转到错误。请任何人检查此代码并指出我失踪的地方。提前谢谢!

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click

    Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")

    Dim dadPurchaseInfo As New SqlDataAdapter
    Dim dsPurchaseInfo As New DataSet1
    Try
        Dim dRow As DataRow

        conxMain.Open()

        Dim cmdSelectCommand As SqlCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
        cmdSelectCommand.CommandTimeout = 30

        dadPurchaseInfo.SelectCommand = cmdSelectCommand
        Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)

        dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")


        For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
            If CInt(dRow.Item("StockID").ToString()) = 2 Then
                dRow.Item("StockCode") = "Re-Fashion[G]"
            End If

        Next
        dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")

    Catch ex As Exception
        MsgBox("Error : ")
    Finally
        If dadPurchaseInfo IsNot Nothing Then
            dadPurchaseInfo.Dispose()
        End If

        If dsPurchaseInfo IsNot Nothing Then
            dsPurchaseInfo.Dispose()
        End If

        If conxMain IsNot Nothing Then
            conxMain.Close()
            conxMain.Dispose()
        End If
    End Try
End Sub

4 个答案:

答案 0 :(得分:1)

您的dataAdapter是否有更新命令?

(它看起来没有 - 因此它不知道如何更新....)

以下是更新命令示例:(对于包含3列的员工表 - 如下所示:

UPDATE [Employee]
SET [name] = @name
  , [manager] = @manager
WHERE (([id] = @Original_id) AND 
      ((@IsNull_name = 1 AND [name] IS NULL) OR
                             ([name] = @Original_name)) AND
      ((@IsNull_manager = 1 AND [manager] IS NULL) OR
                               ([manager] = @Original_manager)));


SELECT id
     , name
     , manager
FROM Employee 
WHERE (id = @id)

您可以看到它是一个可以处理任何字段更改的常规更新。

答案 1 :(得分:1)

循环中的条件是否被执行(设置断点!)?抛出的错误在哪里? 什么错误?

另外,为什么它会使用ToString?这似乎是多余的。

If CInt(dRow.Item("StockID")) = 2 Then

应该够了。

最后,您正在执行冗余清理:

If conxMain IsNot Nothing Then
    conxMain.Close()
    conxMain.Dispose()
End If

Dispose暗示Close - 无需执行这两项操作:

  

CloseDispose功能相同。

[Source: MSDN]

答案 2 :(得分:0)

我从Konard Rudolph的程序纠错中得到了它!

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click

    Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")

    Dim dadPurchaseInfo As New SqlDataAdapter
    Dim dsPurchaseInfo As New DataSet1
       Try
            Dim dRow As DataRow

            conxMain.Open()

            dadPurchaseInfo.SelectCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
            Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)


            dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")

            For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
                If CInt(dRow.Item("StockID")) = 2 Then
                    dRow.Item("StockCode") = "Re-Fashion(H)"
                End If

            Next
            dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")
        Catch ex As Exception
            MsgBox("Error : " & vbCrLf & ex.Message)
        Finally
            If dadPurchaseInfo IsNot Nothing Then
                dadPurchaseInfo.Dispose()
            End If

            If dsPurchaseInfo IsNot Nothing Then
                dsPurchaseInfo.Dispose()
            End If

            If conxMain IsNot Nothing Then
                conxMain.Dispose()
            End If
        End Try
  End Sub

上面的代码集用于使用DataSet进行更新!感谢stackoverflow社区,他回答了我的问题。

这是ref:

p.s:就像o.k.w所说:表必须有主键。谢谢o.k.w!

答案 3 :(得分:-1)

--MENU--
Dim login As New LoginClass
login.ShowDialog()

--CONEXION--
Private conec As SqlConnection
Dim stringCon As String = "Data Source= ;Initial Catalog=;Persist Security Info=True;User ID=;Password="
Public ReadOnly Property prConec() As Object
    Get
        Return conec
    End Get
End Property
Public Sub Conectar()
    Try
        conec = New SqlConnection(stringCon)
        If conec.State <> ConnectionState.Open Then
            conec.Open()
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

--BUSCAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_cliente", funciones.prConec)
Dim dt As New DataTable
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("@i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "B"
dt.Load(coman.ExecuteReader())
grdClientes.DataSource = dt

--INSERTAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_articulo", funciones.prConec)
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("@i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "I"
coman.ExecuteNonQuery()
Buscar()
Limpiar()

--COMBO--
Dim dt As New DataTable
dt.Columns.Add("Codigo")
dt.Columns.Add("Descripcion")
Dim dr1 As DataRow = dt.NewRow
dr1.Item("Codigo") = "A"
dr1.Item("Descripcion") = "Activo"
dt.Rows.Add(dr1)
Dim dr2 As DataRow = dt.NewRow
dr2.Item("Codigo") = "I"
dr2.Item("Descripcion") = "Inactivo"
dt.Rows.Add(dr2)
cmbEstado.DataSource = dt
cmbEstado.ValueMember = "Codigo"
cmbEstado.DisplayMember = "Descripcion"

--GRIDVIEW--
--1--
Dim grdFila As DataGridViewRow = grdClientes.CurrentRow
txtCedula.Text = grdFila.Cells(0).Value
--2--
If DataGridProductos.CurrentCell.ColumnIndex = 0 Then
    Dim FLstArticulos As New FLstArticulos
    FLstArticulos.ShowDialog()
    DataGridProductos.CurrentRow.Cells(0).Value = FLstArticulos.PrIdArticulo
End If

--GRIDVIEW.CELLENDEDIT--
If DataGridProductos.CurrentCell.ColumnIndex = 3 Then
    Dim precio As New Double
    Dim cantidad As New Double
    precio = CDbl(grdRow.Cells(2).Value)
    cantidad = CDbl(grdRow.Cells(3).Value)
    DataGridProductos.CurrentRow.Cells(4).Value = PLTotalFilaItem(cantidad, precio)
    PLCargaTotales()
End If

Sub PLCargaTotales()
    Dim subTotal As Double
    Dim iva As Double
    For Each grd As DataGridViewRow In DataGridProductos.Rows
        If Not String.IsNullOrEmpty(grd.Cells(4).Value) Then
            subTotal = subTotal + CDbl(grd.Cells(4).Value)
        End If
    Next grd
    txtSubtotal.Text = subTotal.ToString
    iva = Decimal.Round(subTotal`enter code here` * 0.12)
    txtIva.Text = iva.ToString
    txtTotalPagar.Text = (subTotal + iva).ToString
End Sub