在ASP:Repeater中查找控件

3
我正在尝试访问Repeater内部的控件。该控件位于<ItemTemplate>标记内。我使用FindControl方法,但它总是返回Null。 我做错了什么?

1
能否发布一下你的 Repeater 示例,这样我们就可以看到发生了什么? - Kev
当我将代码粘贴到Stackoverflow编辑器中时,它会截断代码。 - Server_Mule
只需将其粘贴进来,我们会进行修正。 - Kev
5个回答

5
我猜测FindControl只能在记录级别事件中使用,比如ItemDataBound:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    (ControlTypeCast) e.Item.FindControl("myControl")).SomeProperty = "foo";
}

2

我猜测你可能正在错误的时机查找控件,你需要在ItemDataBound事件中查找。

以下是vb.net示例,但我相信你能理解。

Protected Sub rp_items_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rp_items.ItemDataBound
    If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
        Dim someLiteral As Literal = e.Item.FindControl("someliteral")
    End If
End Sub

0
         for (int i = 0; i <= repeater1.Items.Count - 1; i++)
         {
             Button delete = (Button)repeater1.Items[i].FindControl("btnDelete");
             delete.Visible = true;
             Button edit = (Button)repeater1.Items[i].FindControl("btnEdit");
             edit.Visible = true;
         }    

Vb.net

        For i As Integer = 0 To Repeater1.Items.Count - 1

        Dim CmbTyp As DropDownList = DirectCast(Repeater1.Items(i).FindControl("DropDownList1"),DropDownList)
        Dim SeatN As Label = DirectCast(Repeater1.Items(i).FindControl("label1"), Label)

        styp = CmbTyp.SelectedItem.Text.Trim
        sNo = SeatN.Text



    Next

0
尝试一下
对于vb.net
CType(e.Item.FindControl("myControl"), Literal).Text = "foo"

针对C#

[Literal]e.item.FindControl["myControl"].Text="foo";

0
在大多数情况下,拼写控件名称错误 :) 也可能是您正在搜索存在于另一个容器中的控件。您能发布您的代码吗?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接