asp.netwebforms

Fill GridView with IEnumerable objects


I have an object which looks like this:

public class TestData
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

I have 10 instances of that class stored in a IEnumerable.

I also have a GridView in my aspx file:

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

What I need is a way to display the contents of the IEnumerable in the GridView. But i want to be able to set the "titles" in the thead of the table myself.

So that I get something like this:

<table>
  <thead>
    <th>Firstname</th>
    <th>Firstname</th>
    <th>Telephone</th>
    <th>Email address</th>
  </thead>
  <tbody>
    <!-- the values from each TestData class stored in the IEnumerable -->
  </tbody>
</table>

Can i do this with a GridView or is it better to use some other control for the job? I also remember something about templating? Not sure, I'm pretty new to ASP.NET.


Solution

  • You can use bound field with explicit HeaderText of the bound field.
    Use auto generate columns to false.

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumn="false">
        <asp:BoundField DataField="FirstName" HeaderText="First Name" />
        <asp:BoundField DataField="LastName " HeaderText="Last Name" />
        .....
    </asp:GridView>
    

    Edit 1

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumn="false">
      <Columns>
        <asp:BoundField DataField="FirstName" HeaderText="First Name" />
        <asp:BoundField DataField="LastName " HeaderText="Last Name" />
        .....
      </Columns>
    </asp:GridView>