Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get public string in codebehind into LayoutTemplate of ListView

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.

like image 868
naveen Avatar asked Dec 09 '22 19:12

naveen


1 Answers

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();
}
like image 91
Nikola Bogdanović Avatar answered Jun 01 '23 16:06

Nikola Bogdanović