强类型 GridView

从 Asp.net 4.5 开始,Web 控件可以利用强类型绑定来获得 IntelliSense 支持和编译时错误。

创建一个包含模型的类:

public class Album
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Artist { get; set; }
}

在页面上定义 GridView 控件:

<asp:GridView ID="Grid" runat="server" AutoGenerateColumns="false" ItemType="YourNamespace.Album">
    <Columns>
        <asp:TemplateField HeaderText="Id">
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server" Text="<%# Item.Id %>"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server" Text="<%# Item.Name %>"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Artist">
            <ItemTemplate>
                <asp:Label ID="lblCity" runat="server" Text="<%# Item.Artist %>"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

加载数据并绑定它:

var albumList = new List<Album>
{
    new Album {Id = 1, Artist = "Icing (a Cake cover band)", Name = "Toppings Vol. 1"},
    new Album {Id = 2, Artist = "Fleetwood PC", Name = "Best of Windows"},
    new Album {Id = 3, Artist = "this.Bandnames", Name = "TH_ (Pronounced \"Thunderscore\")"},
};

Grid.DataSource = albumList;
Grid.DataBind();