Reputation: 55248
A doubt in ASP.NET(VB)
I have a public variable in code-behind(ASPX.VB)
Public _orderCode As String = "Hello World"
At ASPX, I would like to access it inline. That too inside the LayoutTemplate of a ListView
<asp:ListView runat="server" ID="listView_OrderReplies"
DataKeyNames="ProductID"
DataSourceID="sdsProducts">
<LayoutTemplate>
<h1>Order Replies for Order Code = <%# _orderCode %></h1>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" ></asp:PlaceHolder>
</LayoutTemplate>
<ItemTemplate>
<b>Name</b>: <%#Eval("ProductName")%><br />
<b>Stock</b>: <%#Eval("UnitsInStock")%><br />
<b>Price</b>: <%#Eval("UnitPrice")%> <br />
</ItemTemplate>
</asp:ListView>
That is, I want this inline binding to succeed
<h1>Order Replies for Order Code = <%# _orderCode %></h1>
or
<h1>Order Replies for Order Code = <%= _orderCode %></h1>
I know it will work inside the page if its not inside a databound control. What I need is a way to access the variable using inline code blocks.
Is it possible? Can anybody point me in the right direction?
BTW, I know to bind it in code-behind and all. I am looking for a specific solution if there is one and a confirmation if there isn't.
Upvotes: 4
Views: 4381
Reputation: 3213
It can be done, and quite easily at that. Just handle OnLayoutCreated
event, and in it call DataBind()
method on LayoutTemplate
control (all child controls will automatically databind as well).
<asp:ListView ID="lv" runat="server" OnLayoutCreated="lv_LayoutCreated">...</asp:ListView>
protected void lv_LayoutCreated(object sender, EventArgs e)
{
lv.Controls[0].DataBind();
}
Just make sure that whatever data is being databound there, it is instantiated before that (on postbacks as well).
Or you can find a specific control in it, and databind just that: lv.Controls[0].FindControl("id").DataBind();
And if you want it databound only on ListView
databinding, than do it in OnDataBound
event - but you must target a control which doesn't contain itemPlaceholder
, or your ItemTemplate
will databind again (with no data this time):
protected void lv_DataBound(object sender, EventArgs e)
{
if(lv.Controls.Count > 0)
lv.Controls[0].FindControl("head").DataBind();
}
Upvotes: 10
Reputation: 1252
This bug is also addressed here: http://www.codeproject.com/KB/aspnet/LayoutTemplate_DataBind.aspx
and here: http://forums.asp.net/p/1201992/3319344.aspx#3319344
The solutions provided here are to extend or adapt the ListView control and properly handle the data-binding of the LayoutTemplate.
Upvotes: 1
Reputation: 25820
It cannot be done or at least I doubt it. My advise, use a literal control or label and assign the text at code-behind.
Check this post . Darko's answer was: Inline code is executed when the page is being rendered ie. after the Page_PreRender event and before the Unload event. Hence after databinding, your inline code is probably a 'goner' for it to work.
Upvotes: 3