Please refer this code:
HTML
<asp:GridView ID="gvOrders" runat="server" OnRowDataBound="gvOrders_RowDataBound"
AutoGenerateColumns="false" HeaderStyle-BackColor="ActiveBorder" AlternatingRowStyle-BackColor="Bisque">
<Columns>
<asp:BoundField DataField="OrderId" HeaderText="OrderId" />
<asp:TemplateField HeaderText="Product Name and Price">
<ItemTemplate>
<asp:GridView ID="Products" runat="server" ShowHeader="false" AlternatingRowStyle-BackColor="LightBlue"
GridLines="None" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ProductName" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="200" />
<asp:BoundField DataField="UnitPrice" ItemStyle-HorizontalAlign="Right" ItemStyle-Width="50" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Total" />
</Columns>
</asp:GridView>
Namespaces
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.PopulateOrdersGrid();
}
}
protected void gvOrders_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string orderId = e.Row.Cells[0].Text;
GridView gvProducts = e.Row.FindControl("Products") as GridView;
this.PopulateProductsGrid(gvProducts, orderId);
decimal total = 0;
foreach (GridViewRow row in gvProducts.Rows)
{
total += Convert.ToDecimal(row.Cells[1].Text);
}
e.Row.Cells[2].Text = total.ToString();
}
}
private void PopulateProductsGrid(GridView gv, string orderId)
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT ProductName, products.UnitPrice FROM Products products INNER JOIN [Order Details] OrderDetails ON OrderDetails.ProductId = products.ProductId " +
"WHERE OrderId = @OrderId"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("@OrderId", orderId);
cmd.Connection = con;
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds);
gv.DataSource = ds;
gv.DataBind();
}
}
}
}
private void PopulateOrdersGrid()
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 3 OrderId FROM Orders"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds);
this.gvOrders.DataSource = ds;
this.gvOrders.DataBind();
}
}
}
}
SQL
I have used northwind database here.
Install the Northwind and Pubs Sample Databases in SQL Server Express
Screenshot
