Kye
Kye

Reputation: 6239

How to get the bound item from within an ASP.NET repeater

I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:LinkButton  Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
        </asp:LinkButton> 
    </ItemTemplate> 
</asp:Repeater>

protected void Page_Load(object sender, EventArgs e)
{
    var list = new List<TestObject>();
    list.Add(new TestObject() {TestValue = "testing1"});
    list.Add(new TestObject() { TestValue = "testing2" });
    list.Add(new TestObject() { TestValue = "testing3" });

    this.Repeater1.DataSource = list;
    this.Repeater1.DataBind();
}

public void Repeater1_DataBinding(object sender, EventArgs e)
{
    var link = sender as HyperLink;
    //link.DataItem ???
}

Is there anyway to find out what the current rows bound item is?

Upvotes: 3

Views: 6902

Answers (3)

Kelsey
Kelsey

Reputation: 47726

I assume you are trying to get the value for the row that is currently being databound?

You can change your function to:

public void Repeater1_DataBinding(object sender, EventArgs e) 
{ 
    var link = sender as HyperLink;
    string valueYouWant = Eval("TestValue").ToString();

    // You could then assign the HyperLink control to whatever you need
    link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
} 

valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.

Upvotes: 3

Chris
Chris

Reputation: 27599

The MSDN library had this as a sample event handler:

public void BindData(object sender, EventArgs e)
{
    Literal l = (Literal) sender;
    DataGridItem container = (DataGridItem) l.NamingContainer;
    l.Text = ((DataRowView) container.DataItem)[column].ToString();

}

(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)

As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)

Upvotes: 1

Sergej Andrejev
Sergej Andrejev

Reputation: 9403

Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available

this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;

void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    var dataItem = e.Item.DataItem;
}

Upvotes: 5

Related Questions