dragonfly
dragonfly

Reputation: 17773

Initialize User Control property value with inline tag

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?

Upvotes: 3

Views: 1750

Answers (1)

codingbiz
codingbiz

Reputation: 26386

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:

Upvotes: 2

Related Questions