c# - error using FindControl on div id

前端 未结 4 1149
小蘑菇
小蘑菇 2021-02-15 14:32

I have an ASP.NET site that I am trying to access div elements by their ID from the C# code behind file. Essentially I want to see if a div element exists, and if so, alter its

相关标签:
4条回答
  • 2021-02-15 15:10

    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?

    0 讨论(0)
  • 2021-02-15 15:15

    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.

    0 讨论(0)
  • 2021-02-15 15:19

    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.

    0 讨论(0)
  • 2021-02-15 15:26

    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

    0 讨论(0)
提交回复
热议问题