Search code examples
c#asp.netsitecoresitecore-dms

Field property is required. All field web controls require the field name to be set


I am assigning the field name of Sitecore image control dynamically from code behind file like below:

.ascx

<sc:Image runat="server" ID="scImgRelatedArticle"></sc:Image>

.ascx.cs

if(currentItem != null)
{ 
Sitecore.Web.UI.WebControls.Date scDateArticleDate = e.Item.FindControl("scDateArticleDate") as Sitecore.Web.UI.WebControls.Date;
                    if (scDateArticleDate != null)
                    {
                        if (DisplayDates)
                        {
                            scDateArticleDate.Field = StartDateFieldName;
                            scDateArticleDate.Item = currentItem;
                        }
                    }
}

Sometimes current Item is null i don't want to assign any field value. I dont want to display the item. But i am ending up with an error message "Field property is required. All field web controls require the field name to be set."

Is there a way in sitecore to do this automatically if i didn't specify the scDateArticleDate.Item property.


Solution

  • You should always set the Field property

    scDateArticleDate.Field = StartDateFieldName // where is a string right!
    

    Then you control the visibility of the item depending on if you have or not the item.

    Also notice you post a image in your ascx and a date field in the .cs

    the complete code would be

    scDateArticleDate.Field = StartDateFieldName; //always set the field
    
    if(currentItem != null)
    { 
             Sitecore.Web.UI.WebControls.Date scDateArticleDate = e.Item.FindControl("scDateArticleDate") as Sitecore.Web.UI.WebControls.Date;
             if (scDateArticleDate != null)
             {
                    if (DisplayDates)
                    {
                        scDateArticleDate.Item = currentItem;
                        scDateArticleDate.Visible = true;
                    }
                    else
                    {
                        scDateArticleDate.Visible = false;
                    }
             }
    }
    

    cheers