Working around "Cannot create an object of type 'System.Boolean' from its string representation"
In ASP.NET Web Forms most times there’s a need to set ASP.NET Server Control properties at runtime. This, for instance:
<asp:Button runat="server" id="Button1" visible="true" />
It is pretty straightforward to set the value of the visible-property in a code-behind page, like so:
protected void Page_Load(object sender, EventArgs e)
{
Button1.Visible = false;
}
However, it would be nice if you could to things like this
<asp:Button runat="server" id="Button1" visible='<% =User.IsInRole("Editor")%>' />
One might expect that that the expression above is evaluated such that the visible-property is true when the current User has the role of Editor and false if not. Unfortunately, executing this bit results in an exception:
Cannot create an object of type 'System.Boolean' from its string representation
'<%= User.IsInRole("Editor") %>' for the 'Visible' property.
These problems are discussed also
here and
here. The reason is that the string-value of each property on a server-control is evaluated and parsed to its desired type. So you could set the property to "True" or "true", but not to an expression that needs to be evaluated.
The solution is to use a databinding syntax, which is pretty easy to do