How do I programmatically set property of control in aspx file?
This may be a very dumb question but I can't seem to get it working. I use at many places the following syntax for dynamically binding a property of a control in aspx file to the resource entry, e.g.
<SomeFunnyControl Text="<%$ Resources : ResClass, ResEntry %>" />
I want to do a similar thing with a class containing some constants, something like
<SomeFunnyControl Text="<%= MyConstantsClass.MyStringConstant %>" />
But this doesn't seem to work, it simply sets the text to the exact expression without evaluating it. I am using ASP.NET 3.5 开发者_如何学运维btw.
I have tried the databinding approach but I get an HttpParseException saying
Databinding expressions are only supported on objects that have a DataBinding event.
This article: The CodeExpressionBuilder might be interesting/helpful (although written for ASP.NET 2.0).
It (seems) to enable you to write ... Text="<%$ Code: DateTime.Now %>" ...
. That might help, no? It is quite a bit of overhead, though.
Your code should look like this:
<asp:Label ID="lblMyStringConstant" runat="server" Text='<%# MyConstantsClass.MyStringConstant %&>'></asp:Label>
You also need to call DataBinding on that control, like this:
lblMyStringConstant.DataBind();
(It is not necessary if you are calling DataBind on entire Page or parent container of this label, because it will call DataBind for all its children)
<asp:Label ID="lbl" Text="<%# SomeText %>" runat="server" />
Then call lbl.DataBind(); or databind some container of the label.
If you have it like this it should work actually:
public static class MyConstantsClass
{
public static string MyStringConstant = "Hello World!";
}
or alternatively
public class MyConstantsClass
{
public const string MyStringConstant = "Hello World!";
}
If you declare it like
<asp:Label ID="Label1" runat="server" Text="<%= MyNamespace.MyConstantsClass.MyStringConstant %>"></asp:Label>
it won't work and the output will be "<%= MyNamespace.MyConstantsClass.MyStringConstant %>
".
What you could do alternatively is to write it like this:
<asp:Label ID="lblTest" runat="server"><%= MyNamespace.MyConstantsClass.MyStringConstant %></asp:Label>
This works perfectly for me, but note you have to provide the fully qualified namespace to your class in the ASPX definition. At least otherwise it didn't work for me.
精彩评论