c# - error using FindControl on div id

前端 未结 4 1238
小蘑菇
小蘑菇 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: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

    Some text
    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.

提交回复
热议问题