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">
<asp:BoundColumn DataField="..."/>

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

ArrayList list = new ArrayList();
grid.DataSource = list;

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">
<%# Container.DataItem %>


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