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">
<columns>
<asp:templatefield headertext="column">
<itemtemplate>
<asp:literal runat="server" id="customerNames" text="<%# Container.DataItem %>"></asp:literal>
</itemtemplate>
</asp:templatefield>
<asp:commandfield showdeletebutton="True">
</asp:commandfield>
</columns>
</asp:gridview>

This code sets a string collection as datasource and binds it to the gridview:
List<string> list = new List<string>();
list.Add("Customer1");
list.Add("Customer2");
list.Add("Customer3");
list.Add("Customer4");
list.Add("Customer5");
list.Add("Customer6");

this.GridView1.DataSource = list;
this.GridView1.DataBind();

But now is the question: how con you retrieve the value for example in the RowDeleting event. As accustomed to windows forms I tried:
this.GridView1.Rows[e.RowIndex].Cells[0].Text;

but that did not work. To get the correct text I had to use:
((Literal)this.GridView1.Rows[e.RowIndex].Cells[0].Controls[1]).Text;

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...

Hi,

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:
http://www.mindfiresolutions.com/How-to-add-a-TemplateField-to-a-GridView-dynamically-841.php

Hope you find it useful and of assistance.

Thanks,
Bijayani