获取"对象引用未设置为对象的实例"错误w / SQL插入

时间:2014-10-22 16:33:01

标签: asp.net vb.net sql-server-2008

以下是我正在使用的代码:

Dim DAL As New DAL.DataAccess, strSQL As String = ""
Dim req = System.Web.HttpContext.Current()
Dim Staff = req.Session("spinUserID")
Dim retID
Dim i

If VisitID.Text = "" Then
    strSQL = "INSERT INTO tblAgentVisit (StatusID, DeadlineDate, Objective, ScheduledDate, Location, Summary, Created_user_id)" & _
        " Values (" & _
        Utils.dbText(statusDropdown.SelectedValue) & "," & _
        Utils.DateOrNull(deadlineDate.Text) & "," & _
        Utils.dbText(objectiveTextBox.Text) & "," & _
        Utils.DateOrNull(entryDate.Text) & "," & _
        Utils.dbText(locationText.Text) & "," & _
        Utils.dbText(summaryTextBox.Text) & "," & _
        Staff & ")"
    strSQL = Utils.replaceChars(strSQL)
    retID = DAL.ExecSqlReturnID(strSQL, CommandType.Text)
    VisitID.Text = retID.ToString

    If agentGridView.Rows.Count > 0 Then
        For i = 0 to agentGridView.Rows.Count - 1
            strSQL = "INSERT INTO tblAgentVisitAgents (VisitID, AgtID)" & _
            " Values (" & _
            VisitID.Text & "," & _
            agentGridView.DataKeys(i).Values("agentValue").ToString & ")"
            strSQL = Utils.replaceChars(strSQL)
            DAL.ExecNonQuery(strSQL, CommandType.Text)
        Next
    End If

    If giveawayGridView.Rows.Count > 0 Then
        For i = 0 to giveawayGridView.Rows.Count - 1
            strSQL = "INSERT INTO tblAgentVisitGifts (VisitID, GiftID, GiftQty)" & _ 'this is my issue'
            " Values (" & _
            VisitID.Text & "," & _
            agentGridView.DataKeys(i).Values("giveawayValue").ToString & "," & _
            agentGridView.DataKeys(i).Values("giveawayQty").ToString & _
            ")"
            strSQL = Utils.replaceChars(strSQL)
            DAL.ExecNonQuery(strSQL, CommandType.Text)
        Next
    End If
End If

在最后一节中,strSQL =行失败,并且"对象引用未设置为对象的实例"错误。我已经尝试过排序,并且无法解决问题。有人看错了吗?前两个条目完美无缺。

1 个答案:

答案 0 :(得分:1)

你的第一个for循环,你的for循环引用agentGridView并在循环中使用agentGridView。第二个引用了giveawayGridview,但在循环中使用了agentGridView。这很好地解释了它。

顺便说一句,您应该编写sql来使用参数而不是构建字符串以防止SQL注入攻击。