Richard77
Richard77

Reputation: 21621

How to set the value of a usercontrol's property in ASP.NET?

There are 3 dropdownlists that are being used at several places. So I decided to put them in a userControl.

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="DetailsDropDownList.ascx.vb"
    Inherits="UserControls_DetailsDropDownList" %>

    <asp:DropDownList ID="dedMoth" runat="server"></asp:DropDownList>
    <asp:DropDownList ID="dedDay" runat="server"></asp:DropDownList>
    <asp:DropDownList ID="dedYear" runat="server"></asp:DropDownList>

In the Code behind, I've defined a property so that I capture the value to display.

public DateTime DetailsDate { get; set; }

So I'm setting the property this way: myUserControl.DetailsDate = myObject.myDate

The problem is that no value is being set. When I set the breakpoint, I notice that UserControl's life cycle starts after that of the main page.

I've tried this as well but no luck.

<uc1:DetailsDropDownList runat="server" ID="myUserControl" 
     DetailsDate ="<%= myObject.myDate%>" />

So How do I set the value of a UserControl?

Upvotes: 1

Views: 763

Answers (2)

Mark Fitzpatrick
Mark Fitzpatrick

Reputation: 1624

You need to persist your property. If you don't it's reset each and every single time the page loads, just like any other local variable. You can easily persist into viewstate though like so:

public DateTime DetailsDate
{
     get{
         if(ViewState["DetailsDate"] == null)
         {
              return DateTime.Today;
         }
         else
         {
              return (DateTime)ViewState["DetailsDate"];
         }
     }
     set {ViewState["DetailsDate"] = value;}
}

Upvotes: 1

Raj Karri
Raj Karri

Reputation: 551

Add Page.DataBind(); in Page_Load() event. This will bind page data. Once debugger pass through page load check expected date is coming or not.

Upvotes: 1

Related Questions