Thursday, May 21, 2009

Stringy stringy bang bang

I had a simple scenario: Array of strings bound to a GridView. Initially, with auto generation of columns, this is easy. You get a single column with all the strings in the array. But then I needed to do something practical with it, so thus needed to specify the columns:

<asp:BoundField DataField="?????" />

I noticed that the column header said "Item" when auto generated so I tried that, but it didn't work. So then, I ask myself, what is the data field of a System.String? The only bindable member (public field or property) is .Length. Good to know but useless in this case. The ToString() member is a method so it can't be bound to. But apparently there is an undocumented trick: Use the exclamation point (!) as the datafield value and you'll get the string's value.

<asp:BoundField DataField="!" />

This yields the desired result.

1 comment:

Imar Spaanjaars said...

I keep forgetting that one, so I typically take the easy way out: convert the column to a TemplateColumn and then bind to Container.DataItem. Cheesy, but it works...

[asp:Label ID="Label1" runat="server"
Text='[%# Container.DataItem %]']

I like your solution better though....