2013-02-22 13 views
0

我有將數據插入數據庫的概率。插入數據庫時​​未設置對象變量

Dim PostId As Object = DirectCast(Repeater1.FindControl("lblPostId"), Label) 

我必須使用Findcontrol,因爲頁面自動找不到lblPostId。然後我definy 的InsertCommand和參數是這樣的:

Dim cmd As SqlCommand = conn.CreateCommand() 
     cmd.CommandText = "INSERT INTO [Comments] ([CommentText], [UserName], [PostId]) VALUES (@CommentText, @UserName, @PostId)" 
     cmd.Parameters.Add("@PostId", System.Data.SqlDbType.Int).Value = PostId.Text 
     cmd.Parameters.Add("UserName", System.Data.SqlDbType.NVarChar).Value = Context.User.Identity.Name 
     cmd.Parameters.Add("CommentText", System.Data.SqlDbType.NText).Value = text.Text 
     cmd.ExecuteNonQuery() 

這米HTML,標籤是內部中繼器(由SqlDataSource的綁定):

<asp:Label ID="lblPostId" runat="server" Text='<%# Eval("PostId") %>' /> 

但它返回錯誤,即對象變量或與變量未在PostId參數上設置。我不知道爲什麼? 我該如何解決這個問題?

回答

1
Dim PostId As Object = DirectCast(Repeater1.FindControl("lblPostId"), Label) 

應該

Dim PostId As Label = DirectCast(Repeater1.FindControl("lblPostId"), Label) 

,並始終以添加參數出現

Dim cmd As SqlCommand = conn.CreateCommand() 
     cmd.CommandText = "INSERT INTO [Comments] ([CommentText], [UserName], [PostId]) VALUES (@CommentText, @UserName, @PostId)" 
     cmd.Parameters.Add("@CommentText", System.Data.SqlDbType.NText).Value = text.Text 
     cmd.Parameters.Add("@UserName", System.Data.SqlDbType.NVarChar).Value = Context.User.Identity.Name 
     cmd.Parameters.Add("@PostId", System.Data.SqlDbType.Int).Value = CInt(PostId.Text) 
     cmd.ExecuteNonQuery() 
+0

我固定它,但它仍然在這兩個變量(帖子ID,文本)返回是System.NullReferenceException:未設置爲對象的實例引用一個對象... – jstorm31 2013-02-22 07:42:07

2

當你搜索一箇中繼器內的控制,你應該考慮有多少ItemsTemplate中顯示出來你直放站控制。

FindControl方法

搜索具有 指定id參數

如果您的中繼器返回2行數據的服務器控件的當前的命名容器,那麼你有,中繼器內,兩個'命名容器',每行一個,它們由Items集合中的不同實例表示。

所以,你的代碼來獲取lblPostID應該是以下

Dim PostId As Label = DirectCast(Repeater1.Items(0).FindControl("lblPostId"), Label) 
+0

就是這樣。謝謝 :-) – jstorm31 2013-02-22 09:31:04