[ASP.Net] 使用Dictionary作為ListView的Datasource

  • 9458
  • 0

[ASP.Net] 使用Dictionary作為ListView的Datasource

首先我們創立好一個ListView並定義其樣板,值得注意的是變動的資料欄位為Dictionary中的Key和Value,在我們所希望填入Key和Value的位置使用<%#Eval("Key")%><%#Eval("Value")%>來指定

 


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Listview Sample</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListView ID="ListView1" runat="server" ItemPlaceholderID="itemPlaceHolder">
            <LayoutTemplate>
                <table>
                    <tr>
                        <th>
                            姓名
                        </th>
                        <td>
                            電話
                        </td>
                    </tr>
                    <asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <th>
                        <%#Eval("Key") %>
                    </th>
                    <td>
                        <%#Eval("Value") %>
                    </td>
                </tr>
            </ItemTemplate>
        </asp:ListView>
    </div>
    </form>
</body>
</html>

在Code Behind部分,新增一個Dictionary來作為DataSource,並將其放入ListView1的DataSource中

 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Dictionary<string, string> tmpDataSource = new Dictionary<string, string>()
        {{"Kirk","3939889"},
         {"Ben","8825252"},
         {"Jesse","32454321"},};

        ListView1.DataSource = tmpDataSource;
        ListView1.DataBind();
    }
}

再來看看執行的結果

listview

 

此為簡單範例,進一步還可以應用此例製作巢狀ListView結構的網頁。