Alex Rivera | Logout

How do I bind a GridView to a custom object?

Asked 2011-04-01T19:02:10.283
9

If I have the following ASP.NET code (it's not complete - obviously there's a lot missing, but none of it matters):

    <asp:GridView>
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    My Label: <asp:Label />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    My Text Box: <asp:TextBox />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

And if I have something like this in the CodeBehind:

Private MyListOfObjects As List(Of MyObject)

...

Public Class MyObject

    Public MyTextBoxString as String
    Public MyLabelString as String

End Class

How can I bind the GridView so that one row is equivalent to one item in my MyListOfObjects list, and so that the data will populate and persist across page loads or postbacks? I've never done custom databinding like this before, so a full explanation would be very helpful. All the tutorials I've come across so far only talk about using GridViews directly with Database query results, and that's not what I need.

Thanks!

Edit
Report

1 Answer

8

Just set the datasource of the gridview to your object.

MyGridView.DataSource = myList
MyGridView.DataBind()

Here's a very similiar post:

Binding a method that returns List<employee> to a gridview

Looks like you are using a list in vb.net. Remember lists can hold integers, strings, dates, objects (these include user defined types (your object)). So you can bind a gridview to a list object by setting the datasource property to your list.

In the above example, myList, might hold a ton of employee objects, etc. So assign it to the datasource and .DataBind() and voila a gridview with each row containing your object.

answered 2011-04-01T19:04:27.167

Your Answer