Search code examples
c#.nethtmlcontrols

Can I access the height/width of an HTML control I just created in C#?


I'm creating DIV controls from code behind using this code -

System.Web.UI.HtmlControls.HtmlGenericControl dynDiv =
    new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
dynDiv.ID = "dynDivCode";
dynDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Gray");
dynDiv.InnerHtml = "I was created using Code Behind";
this.Controls.Add(dynDiv);

Once created, I want to access it's height and width. Is it possible to do that? Or has it not been rendered on the screen at this point to have its properties accessible?

EDIT: I want to access the newly created div's(DIV1) width, but I also want to change the width of another div(DIV2) control i created based on DIV1's width. So I want to read and modify the width of 2 different div tags


Solution

  • There isn't a "width" established yet; it will depend entirely on how it's rendered by the client. You can get/set a CSS "style" attribute, or get/set a CSS class that will correctly style the element when it's rendered.

    you should be able to accomplish what you're trying to do with CSS, but if all else fails, you could use Javascript (jQuery) to get the rendered size and use it to resize the other DIV.