如何从用户控件获取父页面中包含的按钮的ID?

时间:2012-02-06 17:10:28

标签: c# asp.net user-controls

我有一个包含在按钮内的用户控件。

我想使用FindControl()查看父页面中是否存在该按钮,但该按钮没有ID。

我尝试过以下代码:

Page.Master.FindControl("ButtonName/Text on button here?")

我有什么方法可以做到这一点吗?

3 个答案:

答案 0 :(得分:2)

  

我想使用FindControl()来查看父按钮是否存在   页面,但该按钮没有ID。

您将无法使用FindControl找到它,因为这要求该元素具有ID并且此按钮是服务器控件(即在标记中设置runat =“server”)

在这样的场景中你唯一能做的就是使用客户端脚本来使用普通的javascript或jQuery来查找元素。

答案 1 :(得分:1)

假设您正在谈论一个asp:Button,如果您想通过文本搜索,可以进行递归查找。

母版页:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 <head runat="server">
     <title></title>
 </head>
 <body>
     <form runat="server">
     <div>
         <asp:Button runat="server" ID="btnTest" Text="Test Button" />
             <asp:ContentPlaceHolder ID="MainContent" runat="server"/>
     </form>
 </body>
 </html>

用于执行递归查找的代码片段

    protected List<Control> FindButton(ControlCollection controls, string buttonText)
    {
       List<Control> foundControls = (from c in controls.Cast<Control>() where c is Button && ((Button)c).Text == "Test Button" select c).ToList();

       if (foundControls.Count > 0)
           return foundControls;
       else
       {
           foreach (Control ctrl in controls)
           {

               if (foundControls.Count == 0)
                   foundControls = FindButton(ctrl.Controls, buttonText);

               if (foundControls.Count > 0)
                break;

           }
           return foundControls;
       }
    }

然后使用:

        List<Control> buttons = FindButton(Page.Master.Controls, "Test Button");
        if (buttons.Count > 0)
        {
            ((Button)buttons[0]).Text = "I found it";
        }

此代码可以通过多种方式进行修改,例如在找到任何按钮后不再停止,继续循环查找所有按钮。它也可以更改为只找到一个按钮并返回它而不是控件列表。您还可以修改查询以查找其他类型的控件。

答案 2 :(得分:1)

  

如果它是动态创建的?你怎么知道身份证是什么?

如果按钮是动态创建的,那么您应该手动为其分配ID。

示例:

protected void Page_Load(object sender, EventArgs e)
{

    Button btnFound = (Button)this.FindControl("myButton");
    if (btnFound != null)
    {
        Response.Write("Found It!");
    }
}

protected void Page_Init(object sender, EventArgs e)
{
    Button btn = new Button()
    {
        ID = "myButton",
        Text = "Click Me"
    };

    this.Controls.Add(btn);
}
祝你好运!

相关问题