找到正确的文本框值

时间:2013-02-28 14:12:13

标签: asp.net html vb.net findcontrol

我在插入数据插入数据库时​​遇到问题。

 <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"   OnItemDataBound="Repeater1_ItemDataBound">
   <ItemTemplate> 
     <!-- Some other data (text...) -->

     <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("PostId") %>' />  

     <asp:TextBox ID="txtAddComment" runat="server" CssClass="textbox"  Width="200px" />
     <asp:Button ID="btnAddComment" runat="server" CssClass="button" Text="Comment"   CausesValidation="false" OnClick="btnAddComment_Click"/>
   </ItemTemplate>
</asp:Repeater>

代码背后:

 Protected Sub btnAddComment_Click(sender As Object, e As EventArgs)
        Dim HiddenField1 As HiddenField = DirectCast(Repeater1.Items(0).FindControl("HiddenField1"), HiddenField)
        Dim txtAddComment As TextBox = DirectCast(Repeater1.Items(0).FindControl("txtAddComment"), TextBox)
        Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString.ToString)
        Try
            If txtAddComment.Text = "" Then
                Exit Sub
            Else
                conn.Open()
                Dim cmd As SqlCommand = conn.CreateCommand()
                cmd.CommandText = "INSERT INTO Comments (PostId, UserName, CommentText) VALUES (@PostId, @UserName, @Text)"

                cmd.Parameters.Add("PostId", System.Data.SqlDbType.Int).Value = CInt(HiddenField1.Value)
                cmd.Parameters.Add("UserName", System.Data.SqlDbType.NVarChar).Value = Context.User.Identity.Name
                cmd.Parameters.Add("Text", System.Data.SqlDbType.NText).Value = MakeLink(HtmlRemoval.StripTagsCharArray(txtAddComment.Text))                    
                cmd.ExecuteNonQuery()            
            End If

        Catch ex As SqlException                
        Finally
            conn.Close()
        End Try
    End Sub

我显示一些文字,文字下方有文字框和评论按钮。我在hiddenfield中绑定textId以插入注释。代码工作正常,但我只能为转发器显示的数据库中的第一行添加注释。当我想为其他行添加注释(2,3 ...)时,页面会刷新,TextBox中的文本会保留在那里。

这行代码存在问题:

Dim txtAddComment As TextBox = DirectCast(Repeater1.Items(0).FindControl("txtAddComment"), TextBox)

HiddenField的ID是对的。但是代码没有执行,因为页面上第一个文本框的引用上面的行和他的值为null。

当我更改这样的代码行时:

  Dim txtAddComment As TextBox = DirectCast(Repeater1.FindControl("txtAddComment"), TextBox)

它返回错误,对象引用未设置为对象的实例

如何获得具有正确价值的正确文本框? 谢谢你的回答

1 个答案:

答案 0 :(得分:1)

将发件人转发给发送它的按钮,然后从父级获取文本框。例如:

Protected Sub button_click(ByVal sender As Object, ByVal e As EventArgs)
   Dim myButton As button= CType(sender, button)
   Dim myTextBox as TextBox = CType(myButton Parent.FindControl("buttonName"), TextBox)

end sub