How do I pass values to properties ? (eg StartYear='<%=DateTime.Now.Year%>')

A

Alan Silver

Hello,

I have a user control that has a property StartYear. Logically enough,
this takes an Int32 value. I have no problem doing something like ...

<ctls:fred id="frdFred" StartYear="2000" Runat="Server" />

but if I try ...

<ctls:fred id="frdFred" StartYear='<%=DateTime.Now.Year%>'
Runat="Server" />

I get an error "Cannot create an object of type System.Int32 from its
string representation '<%=DateTime.Now.Year%>' for the StartYear
property".

I tried converting it like this ...

<ctls:fred id="frdFred"
StartYear='<%=Convert.ToInt32(DateTime.Now.Year)%>' Runat="Server" />

but got the same error.

Any ideas how I get around this? I thought DateTime.Now.Year returned an
Int32, so I have no idea why it thinks it's a string.

TIA
 
A

Alan Silver

Alan, you must do this in code via fdrFred.StartYear = DaeTime.Now.Year

That's a pain. Is there any reason why I can't do it in the tag?

Thanks for the reply.
 
K

Karl Seguin

i believe it's a timing issue. The server control is parsed and turned into
an object (so that you can do nice things in codebehind) well before asp.net
parses <%= %> so the it sees <%= %> as an actual literla value. It really
isn't a pain, it helps improve readability and maintainability... If you
are going to hard code a value, you should do so in the usercontrol....not
the instantiator..

Karl
 
A

Alan Silver

i believe it's a timing issue. The server control is parsed and turned into
an object (so that you can do nice things in codebehind) well before asp.net
parses <%= %> so the it sees <%= %> as an actual literla value. It really
isn't a pain, it helps improve readability and maintainability... If you
are going to hard code a value, you should do so in the usercontrol....not
the instantiator..

Yeah but sometimes you want to pass default values in which will vary
from tag to tag, and it's just convenient to do that in the tag. For
example, I have just finished a control to show the date and time as
five drop downs. On the page where I used it, some of the instances of
it want the year range to be the last five, some need it to be the next
five. I know they can easily be done in the code, it just seemed easier
to put the values with the tag.

I guess it's just a case of getting into a new way of thinking. Thanks
for the reply.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top