将数据绑定到嵌套的ListView

时间:2014-09-24 14:42:40

标签: c# asp.net .net database listview

我正在创建一个asp.net页面,允许用户搜索多个数据库。

如果找到匹配项,我希望数据库名称在主ListView中返回。然后,我想在其相应的数据库名称下显示与嵌套ListView中的搜索条件匹配的任何公司。

e.g。搜索:公司

结果

数据库1名称
公司123
公司Abc

数据库2名称
公司Xyz

数据库3名称
公司测试

我如何引用和填充嵌套的ListView?

1 个答案:

答案 0 :(得分:3)

您可以使用 Parent ListView OnItemDataBound 事件,并绑定 Child ListView

enter image description here

<asp:ListView ID="DatabaseListView" runat="server"
    OnItemDataBound="DatabaseListView_ItemDataBound">
    <ItemTemplate>
        <h1><%# Eval("Name") %></h1>
        <asp:ListView ID="CompanyListView" runat="server">
            <ItemTemplate>
                <p><%# Eval("Name") %></p>
            </ItemTemplate>
        </asp:ListView>
        <hr />
    </ItemTemplate>
</asp:ListView>

代码背后

public class Database
{
    public string Name { get; set; }

    public IList<Company> Companies;

    public Database()
    {
        Companies = new List<Company>();
    }
}

public class Company
{
    public string Name { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var databases = new List<Database>
        {
            new Database
            {
                Name = "Database 1 Name",
                Companies = new List<Company>
                {
                    new Company {Name = "123"},
                    new Company {Name = "Abc"}
                }
            },
            new Database
            {
                Name = "Database 2 Name",
                Companies = new List<Company> {new Company {Name = "Xyz"}}
            },
            new Database
            {
                Name = "Database 3 Name",
                Companies = new List<Company> {new Company {Name = "Test"}}
            },
        };

        DatabaseListView.DataSource = databases;
        DatabaseListView.DataBind();
    }
}

protected void DatabaseListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        var database = e.Item.DataItem as Database;
        var companyListView = e.Item.FindControl("CompanyListView") as ListView;

        companyListView.DataSource = database.Companies;
        companyListView.DataBind();
    }
}