Nitin Singh
Nitin Singh

Reputation: 159

How to get code behind variable value into repeater itemtemplate

I have a variable in my code behind file in asp.net say string str = "MY Name";

I want to bind this string to a label that is inside the in Repeater.

    <asp:Label  ID="lblsubjects" runat="server" Text='<%# What to  write here %>'/>

The Repeater is binded using a linq query.

Upvotes: 1

Views: 5049

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460138

The property needs to be at least protected, then you can access it inline:

<asp:Label  ID="lblsubjects" runat="server" Text='<%# MyStr %>' />

Codebehind:

private string _MyStr = "MY Name";
protected string MyStr
{
    get
    {
        return _MyStr;
    }
    set
    {
        _MyStr = value;
    }
}

Note that %# is for databinding context only. So there must be somewhere a DataBind on the container control of the label. If it wasn't in the GridView but on the top level of the page you need this.DataBind().

Upvotes: 2

Ashwini Verma
Ashwini Verma

Reputation: 7525

use OnItemDataBound to access Label.

<asp:Repeater ID="Myrp" runat="server" OnItemDataBound="R1_ItemDataBound">

code behind :

public void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
    string str = "MY Name";

    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        ((Label)e.Item.FindControl("lblsubjects")).Text = str;
    }
}

Upvotes: 2

SpiderCode
SpiderCode

Reputation: 10122

See below sample :

Code Behind :

protected string myString;

protected void Page_Load(object sender, EventArgs e)
{
    myString = "My Name";

    string[] data = new[] { "1", "2", "3" };

    this.rep.DataSource = data;
    this.rep.DataBind();
}

ASPX :

<asp:Repeater runat="server" ID="rep">
    <ItemTemplate>
        <div>
            <asp:Label runat="server" Text="<%#myString %>"></asp:Label>
        </div>
    </ItemTemplate>
</asp:Repeater>

Upvotes: 3

Related Questions