使用 LinqDataSource 嵌套 Gridview
在这里,我将解释如何将 Gridview 嵌套在另一个 Gridview 中,例如类别和产品。
引言
在本文中,我将讨论使用 LinqDataSource
和 LinqToSql
创建两个嵌套的 gridview
。 这可以通过多种方式完成,但这是非常简单的一种方法。
让我们看一下截图
Using the Code
我将逐步解释
- 创建
LinqToSql
类,并放入两个表,Categories
和Products
- 在
WebPage
中,创建一个新的GridView
并将其命名为GridView1
。 - 创建
LinqDataSource
,并配置它从Category
表中获取CategoryName
。到目前为止,
gridview
将会是这样的 - 在前面的步骤中,我们创建了一个带有单个
Column
的GridView
,并将其绑定到CategoryName
。因此,我们需要在第二列中放置另一个
Gridview
,第二个Gridview
将包含属于第一列中提到的类别的Products
,因此我们将创建TemplateField
并将GridView
放在其中。然后在该字段内添加
GridView
。 - 创建另一个 Linq
DataSource
并按如下方式配置它使
DataSource
接收参数CategoryID
,稍后我们将以编程方式将datasource CategoryID
传递给它。这里,
LinqDataSource
将根据CategoryID
参数选择Product
,该参数被识别为WhereParameter
- 目前,我们除了将
GridView
放在第二列并创建另一个LinqDataSource
来按类别 ID 获取产品之外,什么都不做。 在下一步中,我们希望将LinqDataSource
的CategoryID
传递给第一列中的categoryName
。 因此,我们获取第一列的CategoryName
的CategoryID
并将其作为WhereParameter
传递给LinqDataSource
,这将在GridView RowCreated
事件中发生,以在创建每一行时更新LinqDataSource
并绑定该行的Gridview
。在
RowCreated EventHandler
中,我们将提供LinqDataSource CategoryID
并Bind Gridview
到 LinqDataSource
。protected void Categories_RowCreated(object sender, GridViewRowEventArgs e) { var db = new NorthWindDataContext(); if (e.Row.RowType == DataControlRowType.DataRow) { GridView GridView2 = (GridView)e.Row.Cells[1].FindControl("Products"); var cat = db.Categories.Single(c => c.CategoryName == Categories.DataKeys[e.Row.DataItemIndex].Value.ToString()); ProductsLinq.WhereParameters["CategoryID"].DefaultValue = cat.CategoryID.ToString(); GridView2.DataSource = ProductsLinq; } }
让我们讨论一下之前的代码
GridView GridView2 = (GridView)e.Row.Cells[1].FindControl("Products");
这里,我们创建对内部 Gridview
的引用以对其进行处理,它位于第二列。
var cat = db.Categories.Single(c => c.CategoryName == Categories.DataKeys
[e.Row.DataItemIndex].Value.ToString());
这里,我们使用 LinqQuery 获取第一列中的 CategoryName
的 Category Object
。
e.Row.DataItemIndex
这意味着当前行,如果您的第一行被创建,它将获取第一个类别以获取其 ID。
ProductsLinq.WhereParameters["CategoryID"].DefaultValue = cat.CategoryID.ToString();
这里,我们将当前行的 CategoryID
传递给 LinqDataSource
GridView2.DataSource = ProductsLinq;
使用 LinqDataSource
绑定 GridView
历史
- 2008 年 10 月 1 日:初始版本