5.25.2004

Binding a DataGrid to an arraylist of strings

...or any simple value type for that matter.

A friend of mine asked me this question and of course it sounds simple. All he wanted to do was:
<asp:Datagrid id="grid" runat="server">
<Columns>
<asp:BoundColumn DataField="..."/>
</Columns>
</asp:Datagrid>

The question was what to put as the DataField, since he's binding an arraylist of strings, as in:

ArrayList list = new ArrayList();
list.Add("1");
list.Add("2");
list.Add("3");
grid.DataSource = list;
grid.DataBind();

What indeed? There's no property on the string data type that returns the string. Doing a little google searching didn't turn up anything satisfactory. One idea was to wrap up the array list into a hashtable (where you can use Key/Value), or to make a custom class and bind that. Yuck, thats a hack! It isn't reusable at all -- and most importantly, it might be a designer messing with the aspx (or ascx) page, and they can't and shouldn't have to write code to accomplish the task. Here's what I would consider the "right" way, which requires zero code changes:

<asp:Datagrid id="grid" runat="server">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<%# Container.DataItem %>
</ItemTemplate>
<asp:TemplateColumn>
</Columns>
</asp:Datagrid>

1 Comments:

Blogger Infinity88 said...

The syntax supported in calls to 'Eval' just supports basically dot notation and indexers to get at properties. It would be nice if just a "." meant "the object itself". If it did, then DataField="." would have worked here.

July 28, 2006 6:36 PM  

Post a Comment

Links to this post:

Create a Link

<< Home