SQL Server数据库未获得更新

时间:2014-01-31 17:13:46

标签: sql-server vb.net datagridview

我使用以下代码,但数据库没有更新:

Dim update As New SqlCommand("Update FAGR SET FAGRN=@FAGRN,FAGRU=@FAGRU WHERE FAGRC=@FAGRC", connection)

update.Parameters.Add(New SqlParameter("@FAGRC", SqlDbType.NChar, 3))
update.Parameters.Add(New SqlParameter("@FAGRN", SqlDbType.NVarChar, 50))
update.Parameters.Add(New SqlParameter("@FAGRU", SqlDbType.NChar, 3))

Dim i As Integer
i = 0
Do While i < DataGridView1.Rows.Count
    Try
        update.Parameters(0).Value = DataGridView1.Rows(i).Cells(0).ToString
        update.Parameters(1).Value = DataGridView1.Rows(i).Cells(1).ToString
        update.Parameters(2).Value = DataGridView1.Rows(i).Cells(2).ToString
        vartemp1 = update.ExecuteNonQuery()
        i=i+1

    Catch ex As Exception
        MsgBox("Exception:" & vbCrLf & ex.Message)
    Finally
        Me.Close()
    End Try
Loop

'在类似的插入查询中,第一行网格被插入数据库中。其他记录没有插入,但也没有出现错误。

2 个答案:

答案 0 :(得分:0)

尝试使用ForEach

  

&#39;在一个类似的插入查询中,第一行网格被插入   数据库。其他记录没有插入,但也没有错误   示出

 For Each dataGridViewRow As DataGridViewRow In DataGridView1.Rows
 If dataGridViewRow.Index = 0 Then 'hint: this is your temporary textbox
     Update.Parameters(0).Value = dataGridViewRow.Cells(0).ToString()
     'Others Stuff
     'vartemp1 = Update.ExecuteNonQuery()

     Exit For
 End If

下一步

希望它会有所帮助。

答案 1 :(得分:0)

首先,请确保您引用了正确的列:

Dim fagrc As DataGridViewColumn = DataGridView1.Columns("FAGRC")
Dim fagrn As DataGridViewColumn = DataGridView1.Columns("FAGRN")
Dim fagru As DataGridViewColumn = DataGridView1.Columns("FAGRU")

DataGridViewCell.ToString不返回单元格值。来自反射器:

Public MustInherit Class DataGridViewCell

    Public Overrides Function ToString() As String
        Return String.Concat(New String() {"DataGridViewCell { ColumnIndex=", Me.ColumnIndex.ToString(CultureInfo.CurrentCulture), ", RowIndex=", Me.RowIndex.ToString(CultureInfo.CurrentCulture), " }"})
    End Function

End Class

这样做:

Dim id As String = Nothing

For Each row As DataGridViewRow In DataGridView1.Rows
    If (Not row.IsNewRow) Then
        id = row.Cells(fagrc.Index).Value.ToString()
        If (String.IsNullOrEmpty(id)) Then
            Throw New ApplicationException("FAGRC missing.")
        Else
            update.Parameters(0).Value = id
            update.Parameters(1).Value = row.Cells(fagrn.Index).Value.ToString()
            update.Parameters(2).Value = row.Cells(fagru.Index).Value.ToString()
            If (update.ExecuteNonQuery() <= 0) Then
                Throw New ApplicationException("Could not update FAGRC with value '" & id & "'.")
            End If
        End If
    End If
Next