Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize User Control property value with inline tag

Tags:

asp.net

I've just written a ASP .NET wrapper for jQuery UI control as user control. It can be used like this:

<ui:DatePicker ID="startDate" runat="server" LabelText="Start Date:" />

Currently I set initial value of this control in Page_Load handler, just like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            startDate.Value = DateTime.Now.AddMonths(-2);
        }
    }

But I thought that it would be nice to move initialization code to markup. Yet I can't work out is how to set initial value of this control using inline tag, for instance:

<ui:DatePicker ID="startDate" Value='<%= DateTime.Now.AddMonths(-2) %>' runat="server" LabelText="Start Date:" /> 

I have a property:

    public DateTime? Value 
    {
        get
        {
            DateTime result;
            if (DateTime.TryParse(dateBox.Text, out result))
            {
                return result;
            }
            return null;
        }
        set
        {
            dateBox.Text = value != null ? value.Value.ToShortDateString() : "";
        }
    }

I've tried different inline tags combinations, and I always get a compilation error. Is there a way to achieve it with inline tags?

like image 389
dragonfly Avatar asked Mar 30 '26 02:03

dragonfly


1 Answers

You will need to put the actual date representation in the property. The reason is that some properties of Asp.Net controls also behave like that e.g. the visible property of a TextBox cannot be set like <asp:TextBox runat="server" Visible='<%= true %>'></asp:TextBox>

 <ui:DatePicker ID="startDate" Value='20/10/2012' runat="server" LabelText="Start Date:" /> 

Or set the value from your Page_Load

  protected void Page_Load(object sender, EventArgs e)
  {
     if(!Page.IsPostBack)
     {
      startDate.Value = DateTime.Now; //initialize DatePicker
     }
  }

I found these link:

  • Why will <%= %> expressions as property values on a server-controls lead to a compile errors?
  • Set Visible property with server tag <%= %> in Framework 3.5
like image 66
codingbiz Avatar answered Apr 03 '26 17:04

codingbiz