c# - error using FindControl on div id

♀尐吖头ヾ 提交于 2019-12-03 12:42:29

If your page is using a MasterPage, the div control will not be in the main collection of controls. That collection only contains the Content controls pointing to the ContentPlaceholder of your MasterPage.

There are three options:

  1. Use FindControl on the Content control: contentControl.FindControl("button1");
  2. Do a recursive FindControl until you find the control you need
  3. Normally, a declaration of your div control is added to your designer.cs codebehind, so you can directly access the control by its name: button1.Attributes["class"] = "classNameHere";

Update

I have created a MasterPage, added a Content Page to it, and added <div id="button1" runat="server">Some text</div> to the Content Page.

In the codebehind of my Content Page, I added this code:

protected void Page_Load(object sender, EventArgs e)
{
    var control = FindHtmlControlByIdInControl(this, "button1");

    if (control != null)
    {
        control.Attributes["class"] = "someCssClass";
    }
}

private HtmlControl FindHtmlControlByIdInControl(Control control, string id)
{
    foreach (Control childControl in control.Controls)
    {
        if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase) && childControl is HtmlControl)
        {
            return (HtmlControl)childControl;
        }

        if (childControl.HasControls())
        {
            HtmlControl result = FindHtmlControlByIdInControl(childControl, id);
            if (result != null) return result;
        }
    }

    return null;
}

This works for me.

Ashwin Chandran

You need to add a runat=server attribute to any control that you want to access in code behind. See this article for more help.

Accessing <div> from both javascript and code-behind

I cannot seem to be able to reproduce your problem, any chance your DIV's are within a template control such as UpdatePanel, Repeater, or Grid?

If you add runat=server please add it at last of the div:

This will work

<div id="divBtn" class="mybuttonCass" runat="server">

However, this will not

<div runat="server" id="divBtn" class="mybuttonCass">

By doing that, you can modify any property from codebehind as:

divBtn.Style["display"] = "none";

This works even with masterpages. The div is not included in a masterpage.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!