如何将GridView值传递给VB.net中的SQLCommand参数

时间:2017-06-27 17:09:02

标签: vb.net gridview

我在GridView中有数据被用户批准用于特定数据期间( StartDate ,例如'2017-05-01)。对于每一行,如果选中该行的复选框,则会批准该记录并加上时间戳。如果未选中该框,则记录标有“D”并带有时间戳。未批准的记录需要发表评论,但未批准的记录不需要评论。

问题是我无法运行更新语句,我相信这是因为我设置参数的方式或 StartDate FileNumber EmpID 。我尝试运行基于 UserName EmpID 的简单DELETE语句,并且这些语句都有效。有什么想法吗?

我尝试了 Request.QueryString(“StartDate”) GridUnapprovedRecords.SelectedRow.FindControl(“StartDate”)的一些变体,但我没有祝他们好运。

错误:

The parameterized query '(@UserName varchar(13),@EmpID varchar(4),@StartDate varchar(8000' expects the parameter '@StartDate', which was not supplied.

The Sub:

Protected Sub UpdateSelectedRecords_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim cb As CheckBox
    Dim atLeastOneRowApproved As Boolean = False
    Dim strComment As TextBox
    Dim conString As String = ConfigurationManager.ConnectionStrings("MktDataConnectionString").ToString()
    Dim sqlConn As New SqlConnection(conString)
        sqlConn.Open()
    Dim cmd As New SqlCommand(conString,sqlConn)
        cmd.Parameters.Add("@UserName", SqlDbType.VarChar)
        cmd.Parameters.Add("@EmpID", SqlDbType.VarChar)
        cmd.Parameters.Add("@StartDate", SqlDbType.VarChar)
        cmd.Parameters.Add("@FileNumber", SqlDbType.VarChar)
        cmd.Parameters.Add("@Comment", SqlDbType.VarChar)

    ' Make changes to dtsp_THS_PerfectAttendanceValidation, row by row
    For Each row As GridViewRow In GridUnapprovedRecords.Rows

        ' Select the current row's check box and comment
        cb = CType(row.FindControl("CheckBox1"),CheckBox)
        strComment = CType(row.FindControl("Comment"), TextBox)

        ' Set parameter values for UPDATE statement
        cmd.Parameters("@UserName").Value = Row.Page.User.Identity.Name
        cmd.Parameters("@EmpID").Value = GridUnapprovedRecords.DataKeys(row.RowIndex).Value
        cmd.Parameters("@StartDate").Value = row.Cells(0).Text.ToString() 
        cmd.Parameters("@FileNumber").Value = row.Cells(2).Text.ToString() 
        cmd.Parameters("@Comment").Value = row.Cells(5).Text.ToString() 

        ' Determine which UPDATE statement to run
        If ((Not (cb) Is Nothing) AndAlso cb.Checked) Then
            ' Approved records; RecordType left as NULL; Comment Optional
            atLeastOneRowApproved = true
            If String.IsNullOrEmpty(strComment.Text) Then
                ' Ignores comment
                cmd.CommandText = "UPDATE dtsp_THS_PerfectAttendanceValidation SET UserName = @UserName, ValidationDate = GETDATE() WHERE StartDate = @StartDate AND FileNumber = @FileNumber AND EmpID = @EmpID"
                cmd.ExecuteNonQuery()
            Else
                ' Adds Comment
                cmd.CommandText = "UPDATE dtsp_THS_PerfectAttendanceValidation SET Comment = @Comment, UserName = @UserName, ValidationDate = GETDATE() WHERE StartDate = @StartDate AND FileNumber = @FileNumber AND EmpID = @EmpID"
                cmd.ExecuteNonQuery()
            End If
        Else
            ' Unapproved records; Same update except that RecordType is set to "D"; Comment Required
            cmd.CommandText = "UPDATE dtsp_THS_PerfectAttendanceValidation SET RecordType = 'D', Comment = @Comment, UserName = @UserName, ValidationDate = GETDATE() WHERE StartDate = @StartDate AND FileNumber = @FileNumber AND EmpID = @EmpID"
            cmd.ExecuteNonQuery()
        End If
    Next
    ' Reload the page
    Response.Redirect(HttpContext.Current.Request.Url.ToString(), True)
End Sub

更新:虽然史蒂夫提供了一些很好的建议,但我最终不得不改变我的工作方式,因为我只是不能让值从gridview传递到VB变量。唯一的例外是我用于 Comment 的文本框,在我可以对它做任何事情之前必须经过多重步骤。我尝试使用 row.FindControl(“Comment”)。文本,但这不起作用。

strComment = row.FindControl("Comment")
strComment.Text

获得的经验教训:如果可以的话,避免从gridview获取值。这可能是可能的,但这很难做到。

2 个答案:

答案 0 :(得分:1)

如果StartDate字段有Date类型的列,则不要传递VarChar类型的参数。这将强制数据库按照服务器计算机上的安装规则执行转换。

您应始终使用适合接收列类型的值传递参数

所以开始将参数声明为

cmd.Parameters.Add("@StartDate", SqlDbType.Date)

然后将单元格值转换为日期变量,并使用该日期设置参数的值。无需转换,数据库引擎正确解释日期

Dim start As DateTime
if Not DateTime.TryParse(row.Cells(0).Text, start) Then
   ' Message about invalid date and return
else
   cmd.Parameters("@StartDate").Value = start

答案 1 :(得分:0)

SQL语句和存储过程通常包含在运行时计算的参数。使用参数编写的SQL语句称为参数化SQL语句。

使用SqlDataSource控件时,可以指定使用参数的SQL查询和语句。通过基于在运行时评估的值读取和写入数据库信息,这有助于使数据绑定方案更加灵活。您可以从各种源获取参数值,包括ASP.NET应用程序变量,用户标识和用户选择的值。您可以使用参数来提供数据检索的搜索条件;提供要在数据存储中插入,更新或删除的值;并提供排序,分页和过滤的值。

SelectCommand =“SELECT EmployeeID,LastName,FirstName FROM Employees WHERE EmployeeID = @EmpID”

InsertCommand =“INSERT INTO Employees(LastName,FirstName)VALUES(@ LastName,@ FirstName);

             SELECT @EmpID = SCOPE_IDENTITY()"

UpdateCommand =“UPDATE Employees SET LastName = @ LastName,FirstName = @ FirstName

               WHERE EmployeeID=@EmployeeID"

DeleteCommand =“DELETE Employees WHERE EmployeeID = @ EmployeeID”

ConnectionString =“<%$ ConnectionStrings:NorthwindConnection%>”OnInserted =“EmployeeDetailsS​​qlDataSource_OnInserted”RunAt =“server”>

<asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />

<asp:Parameter Name="EmpID" Direction="Output" Type="Int32" DefaultValue="0"/>

有关详细信息,请参阅https://msdn.microsoft.com/en-us/library/z72eefad.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-3