Update a user control public property on linkbutton click

882 Views Asked by At

I have created a very simple calendar user control that contains a public property which is used to define which month/year to display. My calendar control is placed inside another ascx control (the wrapper control essentially), which includes LinkButton controls used to toggle the calendar control forward and backward one month at a time. If I explicitly define the SelectedDateTime property of the calendar control in the wrapper control at design time, the proper month/year are displayed by the calendar control. However, when I try to set the property value at run time using a Click event on the previous and next LinkButton controls, the calendar control never picks up the new SelectedDateTime value I try to assign to it.

When I run the code in debug mode, the Click event of the LinkButton always happens last - after the value of the SelectedDateTime property of the calendar control has already been set to default and rendered. What am I missing?

The calendar control is placed in the wrapper control just like any old control:

<wsba:CalendarBase ID="CalendarControl" runat="server" />

I created a LinkButton control to select "Next Month", and its corresponding Click event handler like so:

    protected void NextMonthLink_Click(object sender, EventArgs e)
    {
        CalendarControl.SelectedDateTime = CalendarControl.SelectedDateTime.AddMonths(1);            
    }

This is the meat of the calendar control itself:

    public partial class CalendarBase : System.Web.UI.UserControl
{
    public DateTime SelectedDateTime { get; set; }
    public List<Item> SelectedCalendars { get; set; }

    public CalendarBase()
    {
        // default SelectedDateTime to Now if no value was set
        if (SelectedDateTime.Year.Equals(1)) { SelectedDateTime = DateTime.Now; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // grab the month and year from the selectedDateTime
        int selectedMonth = SelectedDateTime.Month;
        int selectedYear = SelectedDateTime.Year;
        ... Do the rest of the stuff to render my control ...
    }
1

There are 1 best solutions below

3
On BEST ANSWER

I'm likely missing something here, but if your Calendar User Control relies of Public Properties to change its output. You should render the control in an event AFTER the Page_Load event. This will ensure that the rendering occurs after any setting of its properties.

You could/should move your Calendar control code from Page_Load to the Page_PreRender event. That way it will always render after other server events have fired and properties changed.

MSDN Page Lifecycle page