Introduction
In this article, I will talk about creating two nested gridview
s, using LinqDataSource
and LinqToSql
. This can be done in many ways, but this is a very simple way.
Let's take a look at the screenshot:
Using the Code
I will explain it step by step:
- Create
LinqToSql
Class and put two tables, Categories
and Products
:
- In
WebPage
, make new GridView
and name it GridView1
.
- Create
LinqDataSource
, and configure it to take CategoryName
from Category
Table.
Till now, the gridview
will be like that:
- In the previous steps, we create a
GridView
with one Column
, and bind it with CategoryName
.
So we need to put another Gridview
in the second column, this second Gridview
will hold Products
that are in category mentioned in first Column
, so we will create TemplateField
and put GridView
in it.
Then add GridView
inside this field.
- Create another Linq
DataSource
and configure it as follows:
Make DataSource
take parameter CategoryID
, we will give the datasource CategoryID
programatically later.
Here, the LinqDataSource
will select Product
s according to CategoryID
parameter which is identified as WhereParameter
:
- At this point, we don't do anything unless we put
GridView
In the second column andccreate another LinqDataSource
which gets products by category ID. In the next step, we want to give LinqDataSource
the CategoryID
of the categoryName
in the First Column. So we get the CategoryID
of the CategoryName
of First Column and pass it to LinqDataSource
as WhereParameter
, this will occur in GridView RowCreated
Event to pass update the LinqDataSource
when each row is created and bind Gridview
of that Row.
In RowCreated EventHandler
, we will give LinqDataSource CategoryID
and Bind Gridview
to Linq DataSource
.
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;
}
}
Let's Discuss the Previous Code
GridView GridView2 = (GridView)e.Row.Cells[1].FindControl("Products");
Here, we make a reference to inner Gridview
to deal with it, it is in the second column.
var cat = db.Categories.Single(c => c.CategoryName == Categories.DataKeys
[e.Row.DataItemIndex].Value.ToString());
Here, we get Category Object
of the CategoryName
in the first Column
using LinqQuery.
e.Row.DataItemIndex
This means Current Row, if your first Row is created so it takes first Category to get its ID.
ProductsLinq.WhereParameters["CategoryID"].DefaultValue = cat.CategoryID.ToString();
Here, we give CategoryID
of Current Row to the LinqDataSource
GridView2.DataSource = ProductsLinq;
Bind GridView
with LinqDataSource
History
- 1st October, 2008: Initial version