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

  • Thread starter Thread starter Alan Silver
  • Start date Start date
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
 
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.
 
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
 
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.
 
Back
Top