The Outer GridView
To create the first (outer) grid, insert a GridView control and specify the data source (Access Database in our example). Select the columns you want to show. I selected carmaker_id and carmaker_name but the second would suffice; you have to select the primary key though, if you want to allow for update and delete operations. Name the GridView gvCars. You should already have the columns you selected as BoundFields, (select "Edit Columns"). Configure the column and set the header to "Car Maker". Up until now there was no coding required.
The Nested GridView
Because the database has two tables with a one-to-many relationship, we naturally want to show the data accordingly. This can be achieved by inserting a second GridView inside the outer one.
Using the GridView's smart tag, add a new column to the first grid and set its type to "TemplateField". Then, again using the smart tag, select "Edit Templates" to edit the item template you just created. Insert a new GridView control into it and name it gvModels. Set the "Show header" property of this grid to False so that you don't get repeated headers in every row of the outer grid. Exit the template editing by selecting "End template editing" in the smart tag.
Unfortunately there is no way of visually binding both GridViews, even in a simple one-to-many relationship. However, it is straightforward to do it through code. Start by creating an event handler for the RowDataBound event of the first GridView (gvCars). All you have to do is type a function name (I named it gvCars_rowDataBound) in the Properties window (select the lightning bolt to see the events). Visual Studio automatically creates the event handler at the Default.aspx.cs file.
Now all you have to do is associate the data you want to show in the inner grid for each row of the outer grid, like this:
protected void gvCars_rowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gv =
(GridView)e.Row.FindControl("gvModels");
AccessDataSource asd = new AccessDataSource(@"App_Data\SkinSample.mdb",
"SELECT carmodel_name,carmodel_engine,carmodel_color FROM carmodel
WHERE carmaker_id=" + ((DataRowView)e.Row.DataItem)["carmaker_id"].ToString());
gv.DataSource = asd;
gv.AutoGenerateColumns = false;
BoundField bfModelName = new BoundField();
bfModelName.DataField = "carmodel_name";
BoundField bfEngine = new BoundField();
bfEngine.DataField = "carmodel_engine";
BoundField bfColor = new BoundField();
bfColor.DataField = "carmodel_color";
gv.Columns.Add(bfModelName);
gv.Columns.Add(bfEngine);
gv.Columns.Add(bfColor);
gv.DataBind();
}
}
see http://www.codeproject.com/KB/aspnet/SkinSample.aspx for details.
-Paresh