2011-07-22 26 views
0

我使用的代碼下面的這段更新的條目:設置UpdateParameter的默認值給出錯誤

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click 
    With SqlDataSource1 
     .UpdateParameters("id").DefaultValue = Request.QueryString("id") 
     .UpdateParameters("pageContent").DefaultValue = edittor.Content 
     .Update() 
    End With 
End Sub 

的問題是說

.UpdateParameters("id").DefaultValue 

對象引用未設置爲一個對象的實例。

我以前用過這種方法(我認爲)。有人可以請解釋爲什麼這是搞砸了,因爲我注意到大多數人在SQL中直接做,如何以正確的方式做到這一點(即更新我的表中的條目)。

回答

1

這不是最好的解決方案,但你可以試試這個。爲此,您不應該在.aspx頁面中包含該參數,否則會引發錯誤。

第一種方法:

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click 
      Dim id As New Parameter 
     id.Direction = ParameterDirection.Input 
     id.Name = "ID" 
     id.DefaultValue = RubricID 

     If SqlDataSource1.UpdateParameters.Contains(id) = True Or SqlDataSource1.UpdateParameters.Count = 1 Then 
      SqlDataSource1.UpdateParameters.Item("ID").DefaultValue = RubricID 
     Else 
      SqlDataSource1.UpdateParameters.Add(id) 
     End If 
     SqlDataSource1.Update()  
End Sub 

第二種方法:

指定的SqlDataSource的參數OnUpdating事件

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click 
    SqlDataSource1.Update() 
    End Sub 

Protected Sub SqlDataSource1_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Updating 
     Dim ID = New SqlParameter("@ID", CType(Page.RouteData.Values("id"), Int16)) 
      e.Command.Parameters.Add(ID) 
    End Sub 
+0

我很困惑,我所應該做這些代碼片段。你能否給我提供一些適用的上下文(即代碼圍繞這個來顯示我所在的位置)。 – FreeSnow

+0

用更多的代碼檢查我的更新。我希望有所幫助。去第二個。在此時,當SqlDataSource1.update()被觸發時,它將觸發SqldataSource1_Updating事件。然後它會捕獲你所有的參數。 – Mitul