2009-11-08 1 views
0

DataSet에서 내 코드 집합이 업데이트되지 않는 이유는 무엇입니까? 그런 다음 오류로 이동합니다. 누구든지이 코드를 확인하고 제가 누락 된 부분을 지적하십시오. 미리 감사드립니다!VB.NET 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 
+0

예외 메시지를 게시 할 수 있습니까? 그리고 코드의 어느 라인이 던져 질까요? –

+0

안녕하세요. 영형. 케이. 다음 는 예외 메시지입니다, 승 나는 -------------------- InvalidOpeartionException가 SelectCommand에 대해 지원되지 않습니다 UpdateCommand에 대한 동적 SQL 생성을 잡혔다있어 키 열 정보를 반환하지 않습니다. ------------ – RedsDevils

+0

@RedsDevils : "주식"테이블에 기본 키 열이 있습니까? –

답변

1

하는 (! 브레이크 포인트를 설정) 루프에 조건이 실행 얻을 않는 경우 오류입니다 던졌습니다? 무엇 오류?

또한 왜 ToString을 사용합니까? 이것은 중복 된 것처럼 보입니다.

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

충분해야합니다.

마지막으로, 당신은 중복 정리 작업을 수행하고 있습니다 :

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

DisposeClose 의미 - 필요가 두 작업을 수행하지 않습니다 :

CloseDispose는 기능적으로 동일합니다.

[Source: MSDN]

+0

감사합니다 Konard Rudolph! 내 프로그램에 대한 오류 수정을 기반으로했습니다! :) 고마워. 해결할 하루 종일 걸립니다! 대단히 고마워! – RedsDevils

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) 

당신이 어떤 분야의 변화를 처리 할 수있는 일반적인 업데이트입니다 볼 수 있습니다

+0

이 부분은 어떻습니까? 각 dRow에 대해 dsPurchaseInfo.Tables ("Stock"). 행 CInt (dRow.Item ("StockID"). ToString()) = 2이면 dRow.Item ("StockCode") = "재 패션 [G] " 끝 부분 다음 그것은 dataAdapter를 업데이 트라고하지? – RedsDevils

+0

어댑터에 선택 명령 (코드 확인)을 지정하면 업데이트 명령을 내릴 수 있습니다. 코드가 데이터를 변경하지만 어댑터가이를 업데이트하기 위해 실행할 명령을 알아야합니다. Visual Studio 마법사를 사용하여 업데이트 명령을 생성하거나 yoursefl을 쓸 수 있습니다. – Dani

+0

dadPurchaseInfo.UpdateCommand = ..... – Dani

0

나는 Konard 루돌프로 내 프로그램의 오류 수정에서 그것을 얻었다!

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 커뮤니티 덕분에 누가 내 질문에 대답했다. 여기

는 심판입니다 :

p.s : o.k.w 말했듯이 : 테이블에 기본 키가 있어야합니다. 감사합니다 .k.w!

-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 
+0

그'--XYZ -'헤더가 주석인지,'# 영역'인지 아니면 그냥 일반 게시물 텍스트인지는 모르겠지만, 컴파일되지 않을 것이므로 수정해야합니다. –

+0

StackOverflow에 오신 것을 환영합니다. 이 코드가 질문에 대답 할 수는 있지만 이유 및/또는이 코드가 질문에 어떻게 대답하는지에 대한 추가 컨텍스트를 제공하면 장기적인 가치가 향상됩니다. –