程式碼如下,用意是把DATAGRIDVIEW的資料insert 到資料庫
偵錯試RUN還是可以正常insert資料,中斷點到END IF時出現
錯誤NullReferenceException並未將物件參考設定為物件的執行個體
錯誤指向 sqlcmd.Parameters第一行
請問是甚麼原因會這樣?(asp.net)
Sub insdatafile()
Dim cn2 As New SqlConnection(My.Settings.tbltw)
cn2.Open()
Dim sqlcmd As New SqlCommand
Dim delstr As String = "delete from Eai104"
sqlcmd.Connection = cn2
sqlcmd.CommandText = delstr
sqlcmd.ExecuteNonQuery()
Dim tran As SqlTransaction
tran = cn2.BeginTransaction
For i As Integer = 0 To DataGridView1.RowCount - 1 Step 1
Try
If DataGridView1.RowCount > 0 Then
sqlcmd.CommandText = "insert into Eai104 (ma01,ma02,ma021,ma58) values (@ma01,@ma02,@ma021,@ma58)"
sqlcmd.Connection = cn2
sqlcmd.Parameters.Clear()
sqlcmd.Parameters.AddWithValue("@ma01", DataGridView1.Rows(i).Cells(0).Value.ToString)
sqlcmd.Parameters.AddWithValue("@ma02", DataGridView1.Rows(i).Cells(1).Value.ToString)
sqlcmd.Parameters.AddWithValue("@ma021", DataGridView1.Rows(i).Cells(2).Value.ToString)
sqlcmd.Parameters.AddWithValue("@ma58", DataGridView1.Rows(i).Cells(3).Value)
sqlcmd.Transaction = tran
sqlcmd.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Next
tran.Commit()
cn2.Close()
cn2.Dispose()
End Sub
那就是那一行的值是NULL,
你要看一下DataGridView裡面的值是什麼...