简体   繁体   中英

How to find a HtmlGenericControl using a Class

I'm trying to figure out how to find a "div" which is in my main .aspx page from a class, is this possible? If so how? I've tried the code below but is not working

HtmlGenericControl step1 = (HtmlGenericControl)Page.FindControl("step1")

I know this is the way I would do it in the code behind file but in this case I want to do it from a class file.

Thank you in advance.

Basically what I'm trying to accomplish is this, I have multiple divs in my page all of the have runtat="server" visible="false" when certain criteria is met I want to be able to change the visible="true". I have this scenario in multiple pages so I want to be able to create a Class and check for the conditions there and through this way make the div visible or un-visible

The div element must have the runat="server" attribute:

<body>
  <form id="form1" runat="server">
    <div id="step1" runat="server"></div>
  </form>
</body>

Now, you can find the control with a method in a separated class, which is called from the code behind class of the page:

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    Class1 class1 = new Class1();
    class1.FindDiv(this);
  }
}

Separated class:

public class Class1
{
  public HtmlGenericControl FindDiv(Page page)
 { 
    HtmlGenericControl step1 = (HtmlGenericControl)page.FindControl("step1");
    return step1;
 }
}

If you use ASP Panel instead of a div u can access it and Panel renders as div. If u give runat="server" to a div u should be able to access it.

You cannot do that if it is not a server side control..

If it is a HTML control you need to set runat="server" attribute to the div to find it in code behind..

Try

HtmlGenericControl div = (HtmlGenericControl)this.FindControl("div1");

Note : In order to make this code work, you need to have runat="server" property at aspx page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM