Adrian Buzea
Adrian Buzea

Reputation: 836

How to access property defined in code-behind from markup in Web Forms User Control

I have a User control (PlacementUI.ascx) that has a property defined in its code-behind.

//PlacementUI.ascx.cs
public partial class PlacementUI : System.Web.UI.UserControl
{
   public PlacementDTO DataItem { get; set; }
}

How can I access that property in the markup ? tried this but it says DataItem does not exist in the current context

<div class= '<%# DataItem.CssClass %>'>

Upvotes: 0

Views: 715

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460118

This is the ugly inline approach:

<div class= '<%# ((PlacementDTO)DataBinder.Eval(Container.DataItem, "DataItem")).CssClass%>'>

other approach, you need to make the div runat=server and give it an ID:

<div runat="server" id="MyDivId">

in codebehind (it is a HtmlGenericControl):

MyDivId.Attributes["class"] = DataItem.CssClass; 

You could also use a Panel which is rendered as div.

<asp:Panel id="MyPanel" runat="server" />

codebehind:

MyPanel.CssClass = DataItem.CssClass;

Upvotes: 1

Related Questions