ASP.NET - 访问嵌套在GridView列中的Repeater?

时间:2012-08-28 20:10:56

标签: asp.net vb.net gridview repeater

我有一个空白的Repeater嵌套在GridView的一列中,并希望使用GridView中的一个按钮,通过后面的代码按需填充Repeater。我在按钮的命令子中引用转发器时遇到了困难。

以下是相关标记:

<asp:GridView ID="Submission" runat="server" AllowPaging="true" AllowSorting="true" />
            <Columns>
                ..........
                <asp:TemplateField HeaderText="Action">
                    <ItemTemplate>
                        <asp:ImageButton ID="AdminEditSubmission" runat="server" ImageUrl="edit_15.png"
                            alt="" OnCommand="loadDetails" CommandArgument="X" />
                    </ItemTemplate>
                </asp:TemplateField>
                ..........
                <asp:TemplateField>
                    <ItemTemplate>
                                <asp:Repeater ID="RptSubmissionDetail" runat="server">
                                </asp:Repeater>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

为了这个小例子,我将简单地尝试用&#34; Hello world&#34;来更新转发器的标题。然而,当它到达最后一行时,我得到了可怕的&#34;对象引用未设置为对象的实例&#34;错误。

    Sub loadDetails(sender As Object, e As CommandEventArgs)
        Dim rpt As Repeater = CType(Page.FindControl("RptsSubmissionDetail"), Repeater)
        Dim tmpHdr As TemplateBuilder = New TemplateBuilder
        tmpHdr.AppendLiteralString("Hello World")
        rpt.HeaderTemplate = tmpHdr
    End Sub

有谁能告诉我如何从我的ImageButton点击子引用这个转发器?我尝试了几个, Page.FindControl(&#34; RptsSubmissionDetail&#34;)只是我最近的尝试。

2 个答案:

答案 0 :(得分:2)

在GridView的RowCommand中,您需要在FindControl上使用GridViewRow

Sub Submission_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
    If e.CommandName = "loadDetails" Then
      ' Convert the row index stored in the CommandArgument
      ' property to an Integer.
      Dim index = Convert.ToInt32(e.CommandArgument)  
      ' Retrieve the row that contains the button clicked 
      ' by the user from the Rows collection.
      Dim row = Submission.Rows(index)  
      Dim repeater = DirectCast(row.FindControl("RptSubmissionDetail"), Repeater)
    End If
End Sub

从ImageButton的点击事件来看,它几乎是一样的。将sender参数投放到ImageButton,将NamingContainer属性投射到GridViewRow。然后使用FindControl,如上所示:

Sub ImageButton_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim img = DirectCast(sender, ImageButton)
    Dim row = DirectCast(img.NamingContainer, GridViewRow)
    Dim repeater = DirectCast(row.FindControl("RptSubmissionDetail"), Repeater)
End Sub

答案 1 :(得分:0)

在ImageButton Click事件中编写以下代码

For Each row As GridViewRow In Submission.Rows
Dim r As Repeater = DirectCast(row.FindControl("RptsSubmissionDetail"), Repeater)           
If r IsNot Nothing Then
          ' do your work
End If
Next

或者如果您想在特定行中找到重复者,可以将其命名为

Dim r As Repeater = DirectCast(Submission.Rows[0].FindControl("RptsSubmissionDetail"), Repeater)  ' Give the right index            
If r IsNot Nothing Then
          ' do your work
End If