2011-03-11 54 views
0
Imports System.Data.SqlClient 

    Dim constr As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" 


Protected Sub GridView1_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles GridView1.RowUpdated 
     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_volvo SET travel = @travel WHERE travelid = @travelid" 
         cmd.CommandText = sql 
         cmd.Parameters.AddWithValue("@travel", 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 

ERROR:對象引用未設置爲對象的實例..GridView的這個更新命令有什麼問題?

+1

不要喊 - 關掉大寫鎖 – 2011-03-11 07:05:03

回答

0

的問題是在拋出異常的母牛。您可以調試您的代碼來檢查值或變量。

0

使用GridView的傳統方式比您嘗試的方式容易得多。這是在.aspx文件,而不是代碼隱藏:

<asp:GridView ID="myGV" DataSourceID="myDS" runat="server"/> 
<asp:SqlDataSource ID="myDS" SelectCommand="..." UpdateCommand="..." runat="server"/> 
0

你的問題是要麼

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

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

或兩者兼而有之。

可能發生的是,當您分配您的lab1或lab4時,它沒有得到任何值,然後當您嘗試分配sql命令參數並給出值lab4.Text時,如果lab4本身爲空,它將會拋出`對象引用未設置爲對象異常的實例。

但這只是一個猜測。爲了瞭解Forsure,你需要設置一個斷點,並調試你的應用程序。在調試時,請在分配lab1和lab4後檢查它們的值。

希望這會有幫助