2012-02-17 89 views
0

我需要在我的asp.net应用程序中的中继器中找到一个控件。asp.net/VB.net:FindControl,而不是按ControlType的ID

目前我正在使用FindControl("IdOfControl"),这是行之有效的。

但我需要找到一个类型的控件(ImageButton)。

我当前的代码:

For Each rptItem As RepeaterItem In myRepeater.Items 
    Dim imgBtn As ImageButton = TryCast(rptItem.FindControl("myImageBtn"), ImageButton) 
    AddHandler imgBtn.Click, AddressOf imgBtn_Click 
Next 

我在寻找类似的东西:

For Each rptItem As RepeaterItem In myRepeater.Items 
    Dim imgBtn As ImageButton = TryCast(rptItem.FindControl(TypeOf ImageButton), ImageButton) 
    AddHandler imgBtn.Click, AddressOf imgBtn_Click 
Next 

有人能帮忙吗?

+1

这里,有一个C#的解决方案。 http://programcsharp.com/blog/archive/2008/01/02/Recursively-find-controls-by-type-with-generics.aspx – AngeloBad 2012-02-17 11:40:22

回答

3

试试这个

您的要求

For Each ri As RepeaterItem In myRepeater.Items 
    For Each cn As Control In ri.Controls 
     If cn.[GetType]() = GetType(ImageButton) Then 
      Response.Write("ss") 
      Response.Write(vbLf) 
     End If 
    Next 
Next 

e.g 
    For Each cn As Control In form1.Controls 
     If cn.[GetType]() = GetType(ImageButton) Then 
      Response.Write("ss") 
     End If 
    Next 
+0

谢谢。这导致我到正确的代码。查看我的答案,以完整的工作代码作为草稿。 – 2012-02-17 12:03:33

0

我不知道,如果你的中继器将嵌套的控制,包含ImageButtons。因此,一些沿下面的递归代码的行:

Public Function FindControl(ByVal ParentControl As Control) As Control 
     Dim ReturnedControl As New Control 
     For Each CurrentControl As Control In ParentControl.Controls 
      CurrentControl.[GetType]() = GetType(ImageButton) Then 
       ReturnedControl = CurrentControl 
       Exit For 
      End If 
      If (CurrentControl.HasControls) Then 
       ReturnedControl = FindControl(CurrentControl) 
      End If 
     Next 
     Return ReturnedControl 
    End Function 

上述功能会发现你已经传过来的参数Repeater控件第一的ImageButton。希望这可以帮助。

0

Sanjay Goswami发布了一个很好的解决方案。

我不得不改变

If cn.[GetType]() = GetType(ImageButton) Then 

If cn.GetType().Equals(GetType(ImageButton)) Then 

,并添加我的东西。

完整的工作代码:

For Each rptItem As RepeaterItem In myRepeater.Items 
    For Each cn As Control In rptItem.Controls 
      If cn.GetType().Equals(GetType(ImageButton)) Then 
       AddHandler (TryCast(rptItem.FindControl(cn.ID), ImageButton)).Click, AddressOf imgBtn_Click 
      End If 
    Next 
Next 
0
For Each cn As Control In Me.Controls 
     If (cn.[GetType]().Equals(GetType(Button))) Then 
      Dim str1 As String = cn.Text 
      ds = fobj.getrecord("select shopid from tbstallbooking where shopid='" + str1 + "'") 
      n = ds.Tables(0).Rows.Count 
      If (n > 0) Then 
       cn.BackColor = Color.Red 
       cn.Enabled = False 
       ds.Clear() 
      Else 
       cn.BackColor = Color.Green 
       cn.Enabled = True 
      End If 
     End If 
    Next 
+0

我想找到一个窗体中的控件,并做出了这种帮助的地图布局 – 2015-03-05 07:43:47