views:

91

answers:

3

I am binding an Object datasource to a grid view. My object has a collection of items in one of the properties.Which is a List. How do I Loop thru this and bind the items to a column in GridView?.

+1  A: 

Get the Collection from the object and bind it by using

myGridView.DataSource = myCollection; 
myGridView.DataBind();
Henrik P. Hessel
A: 

Edit: updated to call a method in the code behind to generate html markup for the collection.

In your aspx markup you could have something like the following:

    <asp:GridView ID="myGridView" AutoGenerateColumns="False" runat="server">
        <Columns>
            <asp:BoundField HeaderText="Item Name" DataField="Name" />
            <asp:TemplateField HeaderText="Collection Field">
                <ItemTemplate>
                    <%# ((_Default)Page).GetHtmlForList(DataBinder.Eval(Container.DataItem, "List"))%>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

then in your code behind you could have something like this:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            myGridView.DataSource = GetCollection();
            myGridView.DataBind();
        }
    }

    public string GetHtmlForList(object value)
    {
        string html = "";
        List<string> list = (List<string>)value;
        foreach (string item in list)
            html += item + "<br/>";
        return html;
    }

    private List<MyClass> GetCollection()
    {
        List<MyClass> coll = new List<MyClass>();
        coll.Add(new MyClass { Name = "First Item", List = new List<string>(new string[] { "1", "2", "3" }) });
        coll.Add(new MyClass { Name = "Second Item", List = new List<string>(new string[] { "Apples", "Pears", "Oranges" }) });
        coll.Add(new MyClass { Name = "Third Item", List = new List<string>(new string[] { "Red", "Green", "Blue" }) });

        return coll;
    }
}

public class MyClass
{
    public string Name { get; set; }
    public List<string> List { get; set; }
}
mdresser
One of the property of my object is a List<SomeObject>. How do I bind the SomeObject in a Column?.
Greens
Thank you very much.
Greens
A: 

Could you not have a Repeater inside the Col. template, and simply bind your List to it in the RowDataBound?

chris