开发者

Accessing bound repeater item from template in asp.net

开发者 https://www.devze.com 2023-04-13 06:22 出处:网络
I have set a list of items as datasource for a repeater and I have created a custom template. Is there any way to directly access the current bound item in the template ?

I have set a list of items as datasource for a repeater and I have created a custom template. Is there any way to directly access the current bound item in the template ? Example code below

class MyObject
{
public string Somevalue{get;set;}
}

Code in my Page_Load

List<MyObject> selections = new List<MyObject>();
                    selections.Add(new MyObject());
                    Repeater1.ItemTemplate = new MyObjectTemplate();
                    Repeater1.DataSource = selections;
                    Repeater1.DataBind();

The template

public class MyObjectTemplate : ITemplate
{
    public void InstantiateIn(Control container)
    {
      //Get the current item
       MyObject o = ????? as MyObject;

       string txt = "<h1>开发者_JAVA百科"+ o.Somevalue + "</h1>";
        LiteralControl h1 = new
            LiteralControl(txt);
        container.Controls.Add(h1);

    }
}

I know that If I just wanted to display the value of "Somevalue" in the repeater there would be easier ways of achieving this, but the actual logic of which values to display and how is more complicated.


You need to use DataItem from the container. For example,

public void InstantiateIn(Control container)
{
   //Get the current item
   MyObject o = ((IDataItemContainer)container).DataItem as MyObject;

   ... 
}

Only issue with this approach is that if you are relying on the view-state on post-back to maintain the control state then the data item will not be of type MyObject. In such case, the best bait would be to use DataBinder - for example,

public void InstantiateIn(Control container)
{
   // Get SomeValue property value
   var val1 = DataBinder.Eval(container, "SomeValue");

   // Get value2 property value
   var val1 = DataBinder.Eval(container, "Value2");

   ... 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号