強型別 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();