Search code examples
asp.netsystem.web.ui.webcontrols

ASP.NET auto width control


I have an ASP.NET control, for example a DropDownList. I want to set the width of the control to auto. How do I achieve this? The Width property in ASP.NET control does not seem to accept auto, but it can only accept like percentage, pixels, and points.

I know I can make some workaround by specifying style="width:auto" as the control's attribute, and as this attribute is not a valid attribute for the control, it will not be parsed by asp.net and hence passed directly to browser. Is there a more proper way to do this?


Solution

  • A few alternatives:

    • Adding the style=width:auto; into the ASP.NET webcontrol, as mentioned in the question
    • Adding element.Attributes.Add('style', 'width:auto'); in the code behind. Generally it is the same as option number 1, just that it's added from code behind. But option 1 seems to be better because it does not mix presentation with code behind, and changing the presentation does not require recompiling of the program.
    • Remove the Width property for the ASP.NET control. If the Width property is not specified, it will be set as auto. But here we need to be careful if there is any CSS rule that may affect the behavior, for example we specify input in the CSS file.