我有3个级别的深层重复器,它们绑定到以下内容:

MainCategories-绑定到顶部中继器

子类别-绑定到第二级的中继器

SubSubCategories-绑定到第三级的中继器

到目前为止,我通过使用中继器的itemdatabound事件并传递类别ID来过滤下面的级别,从而实现了数据绑定(例如:获取MainCategory 1的所有SubCategories,获取MainCategory2的所有Subcategoris)。
当然,这会导致多次访问数据库,并且效率很低。

有没有办法只进行3个查询:
1.获取所有主要类别并绑定到顶部豌豆,
2.获取所有子类别并以某种方式绑定到第二级中继器
3.获取所有子子类别并绑定到第三级中继器。

如何在asp.net C#中实现?

最佳答案

为此,请按照以下步骤操作:

首先将数据放入数据表,说dataTableMainCategories,然后从SubCategories数据表中过滤SubSubCategoriesdataTableMainCategories。最后,在ItemDataBound处编写以下代码块,并为SubCategoriesSubSubCategories DataTable添加所需的列,然后再导入过滤的行。

将所有主要类别填充到一个表中,并绑定到MainCategory中继器(rptrMainCategories),然后将所有子类别和子子类别填充到dataTableCategories数据表中。

protected void rptrMainCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if(e.Item.ItemType== ListItemType.Item)
    {
        int subCategoryID = 5; // Pass your subcategory id to be filtered
        Repeater rptrSubCategories = (Repeater)e.Item.FindControl("rptrSubCategories");
        DataTable dtSubCategory = new DataTable();
        dtSubCategory.Columns.Add(); // Add your columns as SubCatagory
        DataRow[] dataRows = dataTableCategories.Select("SubCategoryID= " + subCategoryID + "");
        foreach (DataRow dataRow in dataRows)
        {
            dtSubCategory.ImportRow(dataRow);
        }
        rptrSubCategories.DataSource = dtSubCategory;
        rptrSubCategories.DataBind();
    }
}

protected void rptrSubCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if(e.Item.ItemType== ListItemType.Item)
    {
        int subSubCategoryID = 55; // Pass your subsubcategory id to be filtered
        Repeater rptrSubSubCategory = (Repeater)e.Item.FindControl("rptrSubSubCategory");
        DataTable dtSubSubCategory = new DataTable();
        dtSubSubCategory.Columns.Add(); // Add your columns as SubCatagory
        DataRow[] dataRows = dataTableCategories.Select("SubSubCategoryID= " + subSubCategoryID + "");
        foreach (DataRow dataRow in dataRows)
        {
            dtSubSubCategory.ImportRow(dataRow);
        }
        rptrSubSubCategory.DataSource = dtSubSubCategory;
        rptrSubSubCategory.DataBind();
    }
}


更新资料

如果使用类型化(自定义类型)数据,则可以通过以下方式选择数据:

//Populate all main categories
public List<Category>  MainCategories { get; set; }

//Populate all sub and sub categories
public List<Category> SubCategories { get; set; }


rptrMainCategories_ItemDataBound事件中,编写以下代码并绑定到转发器:

List<Category> subCategory = SubCategories.Where(c => c.SubCategoryId = yourSubCategoryID);
rptrSubCategories.DataSource = subCategory ;
rptrSubCategories.DataBind();


rptrSubCategories_ItemDataBound事件中,编写以下代码并绑定到转发器:

List<Category> subSubCategory = SubCategories.Where(c => c.SubSubCategoryId = yourSubSubCategoryID);
rptrSubSubCategory.DataSource = subSubCategory ;
rptrSubSubCategory.DataBind();

10-02 09:31