Archive

Posts Tagged ‘eval’

Back To Basics - Container.DataItem

June 16th, 2008

Since asp.net 2.0 was in beta, I pretty much bailed on .NET 1.1 and Visual Studio 2003 and I’ve been pretty happy that way.

One of my favorite features in asp.net 2.0 (it’s a long list after working in 1.1) was the shortened syntax for declarative databinding to objects using Eval(”propertyname”) where “propertyname” is, well, a property in the object being bound to the control. This works when binding to a collection of objects where the values you want to use are stored in properties of the object. What about simple types such as integers or strings?

It’s pretty easy to bind a databound control to a collection of simple types such as a List<string> or a string array but since I don’t do it very often, I have to stop and remember (or look up) how to do it. So for my own reference and anybody else that may find this useful, here is a simple code example:

<ul>
  <asp:Repeater ID="rptSampleStrings" runat="server">
    <ItemTemplate>
      <li>
        <asp:Label runat="server" ID="lblStringDisplay"
          Text='<%#Container.DataItem %>' />
      </li>
    </ItemTemplate>
  </asp:Repeater>
</ul>

Here I have a repeater that will render a bulleted list of items from my List<string>. Notice the use of Container.DataItem for the text property… this is the point of this post. This is the syntax I always have to think about.

This is just to illustrate a point, I know I could use a ListView or the BulletedList control to do this. Anyway, here is the code-behind that creates the List<string> and binds it to the repeater (this code is in the Page_Load event handler):

var sampleStrings = new List<string>();
sampleStrings.Add("Test One");
sampleStrings.Add("Test Two");
sampleStrings.Add("Test Three");
sampleStrings.Add("Test Four");
sampleStrings.Add("Test Five");

//Set repeater datasource
rptSampleStrings.DataSource = sampleStrings;
rptSampleStrings.DataBind();

So, as you can see, it’s very simple to bind control properties to a list of strings, integers, etc. as long as you can remember the syntax.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

.NET, ASP.NET, Back to Basics, programming , , ,