Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style property of custom asp.net control throws exception when set

Tags:

c#

asp.net

I have written custom control that inherits from System.Web.UI.Control. I have added Style property like this:

public class MyControl : Control
{
    public CssStyleCollection Style
    {
        get { return ViewState["Style"] as CssStyleCollection; }
        set { ViewState["Style"] = value; }
    }
}

And I use it the following way

<custom:MyControl runat="server" Style="float: left; padding: 2px 4px;" ... />

When I attempt to load the page, I receive the following exception:

Cannot create an object of type 'System.Web.UI.CssStyleCollection' from its string representation 'float: left; padding: 2px 4px;' for the 'Style' property.

I suppose I should add a TypeConverter attribute to the property or something, but I could not find appropriate one in the System.Web.UI namespace. I also searched google and there was not much information for exactly this issue. I know that this would have worked if I extended WebControl but I'd prefer a solution that deals with Control.

like image 631
Ivaylo Slavov Avatar asked Dec 21 '25 01:12

Ivaylo Slavov


1 Answers

When you're adding styles to an ASP.NET control, you should be able to use the standard style attribute. The attribute will likely be hidden from intellisense, but it's an accepted HTML attribute so it should still work:

<asp:TextBox ID="TextBox1" runat="server" style="font-weight:bold;" />

Behind the scenes, the style attribute will be parsed and the properties will be loaded into the Styles collection:

string weight = TextBox1.Styles["font-weight"]; //== "bold"
like image 97
James Johnson Avatar answered Dec 23 '25 15:12

James Johnson