Binding a Custom Class to a DataGrid

This demo illustrates how to bind a collection of custom classes to a DataGrid.


First NameLast NamePhoneNumber of Visits
ScottMitchell111-222-333320
JisunLeeb111-222-333325
EdNorth111-555-33332
JohnSouth555-555-3322105


Source Code

<%@ Import Namespace="MyObjects" %>

<script runat="server" language="VB">



  Sub Page_Load(sender as Object, e as EventArgs)

    'Create a user collection object

    Dim users as New UserCollection()

    

    'Now, fill it with some users

    users.Add(New UserInfo("Scott","Mitchell","111-222-3333",20))

    users.Add(New UserInfo("Jisun","Leeb","111-222-3333",25))

    users.Add(New UserInfo("Ed","North","111-555-3333",2))

    users.Add(New UserInfo("John","South","555-555-3322",105))

    

    'Now, bind the users collection to the DataGrid

    dgUserList.DataSource = users

    dgUserList.DataBind()

  End Sub



</script>



<form runat="server">

   <asp:DataGrid id="dgUserList" runat="server"

        AutoGenerateColumns="False"

        Font-Name="Verdana"

        

        HeaderStyle-BackColor="Navy"

        HeaderStyle-ForeColor="White"

        HeaderStyle-Font-Bold="True"

        

        AlternatingItemStyle-BackColor="#eeeeee">

        

        <Columns>

            <asp:BoundColumn DataField="FirstName" HeaderText="First Name" />

            <asp:BoundColumn DataField="LastName" HeaderText="Last Name" />

            <asp:BoundColumn DataField="PhoneNumber" HeaderText="Phone" />

            <asp:BoundColumn DataField="Visits" HeaderText="Number of Visits"

                DataFormatString="{0:d}" ItemStyle-HorizontalAlign="center" />

        </Columns>            

    </asp:DataGrid>

</form>


[Return to the article...]