这个代码有什么问题吗?

时间:2011-03-11 06:11:08

标签: asp.net vb.net visual-studio-2008 sqldatasource

我已经编辑过这个但同样的问题:

Protected Sub SqlDataSource1_Updated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
    For Each myRow As GridViewRow In GridView1.Rows
        'Find the checkbox
        Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
        Dim lab4 As Label = DirectCast(myRow.FindControl("Label4"), Label)
        Try
            Using conn = New SqlConnection(constr)
                Using cmd = conn.CreateCommand()
                    conn.Open()
                    Dim sql As String = "UPDATE a1_ticket SET Travels = @travels WHERE travelid = @travelid"
                    cmd.CommandText = sql
                    cmd.Parameters.AddWithValue("@travels", lab4.Text)
                    cmd.Parameters.AddWithValue("@travelid", lab1.Text)
                    cmd.ExecuteNonQuery()
                End Using
            End Using
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
    Next
End Sub

错误:对象参考未设置为对象的实例

2 个答案:

答案 0 :(得分:1)

错误在于此行:Dim strSql As String = "UPDATE a1_ticket SET Travels = '" & lab4.Text & "' WHERE travelid =" & lab1.Text

travelid is Text so it should be travelid='" & lab4.Text & "'".

答案 1 :(得分:1)

我强烈怀疑这将是罪魁祸首:

Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
Dim lab4 As Label = DirectCast(myRow.FindControl("Label4"), Label)

FindControl如果找不到具有该ID的控件,则返回null / Nothing。我的猜测是因为你可能有多行,所以每行中控件的ID都会自动生成并附加额外的信息。我建议您查看页面上的HTML并查看正在生成的内容...您可能希望找到一种更好的方法来查找连续的单个控件。

如评论中所述,您应该参数化SQL语句以避免SQL注入攻击。