Monday, December 1, 2008

Show Collection of strings in GridView

Today I faced the following problem; I had a collection of strings which I wanted to show in a GridView. I tried to use the collection as datasource, but nothing was displayed. A quick and simple solution to this problem is the following:
- First you add a template column to the grid view
- In the template for the item you create a Literal control
- Then the Text property of the Literal is set to DataItem of the Container which is evaluated when databinding occurs

This can be accomplished with the following code:
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" onrowdeleting="GridView1_RowDeleting">
<asp:templatefield headertext="column">
<asp:literal runat="server" id="customerNames" text="<%# Container.DataItem %>"></asp:literal>
<asp:commandfield showdeletebutton="True">

This code sets a string collection as datasource and binds it to the gridview:
List<string> list = new List<string>();

this.GridView1.DataSource = list;

But now is the question: how con you retrieve the value for example in the RowDeleting event. As accustomed to windows forms I tried:

but that did not work. To get the correct text I had to use:

Alltogether the cell contains 3 controls. The other two are LiteralControls with the Text '\r\n ' and the second one is the Literal control which holds the text.

1 comment:

Bijayani said...


I happened to see your post find it quite informative. I would like to share a link where a software engineer has shared a tip on "How to add a TemplateField to a GridView dynamically?". I am just sharing it for the knowledge purpose.

Here is the link:

Hope you find it useful and of assistance.