Search code examples
c#asp.netwebformscustom-server-controls

How To Get A Server Control Property Name With A Dash In It


I'm creating a custom server control in ASP.NET WebForms and want to have a hyphen in my property name the same way the ASP.NET server controls do in the markup. For example, a Label control has a "Font-Size" property in the markup like so:

<asp:Label ID="Label1" Font-Size="small" Text="hi" runat="server" />

How do I accomplish this?


Solution

  • Just use complex properties on your control:

    public class MyControl: WebControl
    {
        public Test()
        {
            // Make sure to initialize the complex property or you will get a NRE
            // when you try to set the Complex-Bar property in the webpage
            Complex = new Complex();
        }
    
        public Complex Complex { get; set; }
    }
    
    public class Complex
    {
        public string Bar { get; set; }
    }
    

    and then:

    <asp:MyControl runat="server" ID="myControl" Complex-Bar="foo bar" />