3

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?

dragonfly
  • 17,407
  • 30
  • 110
  • 219
  • what is the compilation error? – codingbiz Oct 18 '12 at 20:52
  • for instance: Cannot create an object of type 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' from its string representation '<% DateTime.Now %>' for the 'Value' property. – dragonfly Oct 18 '12 at 20:59
  • Read this http://stackoverflow.com/questions/370201/why-will-expressions-as-property-values-on-a-server-controls-lead-to-a-co - It took me time to understand it too – codingbiz Oct 18 '12 at 21:15

1 Answers1

2

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:

Community
  • 1
  • 1
codingbiz
  • 26,179
  • 8
  • 59
  • 96