#region LoadResults /// <summary> /// LoadResults /// </summary> private void LoadResults() { DataRow oRow; DataTable oTable = new DataTable("RESULTS"); string sSQL; SqlDataAdapter oDA = new SqlDataAdapter(); DataSet oDS = new DataSet(); try { //set up columns in the results table oTable.Columns.Add("CompanyName",Type.GetType("System.String")); oTable.Columns.Add("OrderDate",Type.GetType("System.DateTime")); oTable.Columns.Add("ProductName",Type.GetType("System.String")); oTable.Columns.Add("Quantity",Type.GetType("System.Int32")); oTable.Columns.Add("UnitPrice",Type.GetType("System.Decimal")); oTable.Columns.Add("Total",Type.GetType("System.Decimal")); //send a batch of selects as the data adapters SelectCommand sSQL = "SELECT * FROM CUSTOMERS WHERE CompanyName < 'C'" + " SELECT * FROM ORDERS WHERE CustomerID < 'C'" + " SELECT [ORDER DETAILS].OrderId, [ORDER DETAILS].Quantity, [ORDER DETAILS].UnitPrice, ProductName FROM [ORDER DETAILS], PRODUCTS WHERE [ORDER DETAILS].ProductId = PRODUCTS.ProductId"; oDA = new SqlDataAdapter(sSQL, moConn); //map the tables that are returned from the DB to the ones we will create in the dataset oDA.TableMappings.Add("Customers", "Customers"); oDA.TableMappings.Add("Customers1", "Orders"); oDA.TableMappings.Add("Customers2", "Details"); oDA.Fill(oDS, "Customers"); //set up the relationships oDS.Relations.Add("Customer_Order", oDS.Tables["Customers"].Columns["CustomerID"], oDS.Tables["Orders"].Columns["CustomerID"]); oDS.Relations.Add("Order_Detail", oDS.Tables["Orders"].Columns["OrderId"], oDS.Tables["Details"].Columns["OrderId"], false); //loop through the tables getting child rows as necessary foreach (DataRow oCustomerRow in oDS.Tables["Customers"].Rows) { decimal dOrderTotal = 0; oRow = oTable.NewRow(); oRow["CompanyName"] = oCustomerRow["CompanyName"]; oTable.Rows.Add(oRow); foreach (DataRow oOrderRow in oCustomerRow.GetChildRows("Customer_Order")) { oRow = oTable.NewRow(); oRow["OrderDate"] = oOrderRow["OrderDate"]; oTable.Rows.Add(oRow); foreach (DataRow oDetailRow in oOrderRow.GetChildRows("Order_Detail")) { oRow = oTable.NewRow(); oRow["ProductName"] = oDetailRow["ProductName"]; oRow["Quantity"] = oDetailRow["Quantity"]; oRow["UnitPrice"] = oDetailRow["UnitPrice"]; //calculate on the fly oRow["Total"] = (Convert.ToDecimal(oDetailRow["UnitPrice"]) * Convert.ToDecimal(oDetailRow["Quantity"])); oTable.Rows.Add(oRow); //add to running total dOrderTotal += Convert.ToDecimal(oRow["Total"]); } } oRow = oTable.NewRow(); oRow["ProductName"] = "Customer Total"; oRow["Total"] = dOrderTotal; oTable.Rows.Add(oRow); } dgValues.DataSource = oTable; dgValues.DataBind(); SetHierarchical(false); } catch (Exception x) { CommonFunctions.pLogError(x, ConfigurationSettings.AppSettings["errorLog"], "DefaultPage.LoadResults",true); CommonFunctions.pShowError(x.Message, Page, tblErrors); } } #endregion
#region SetHierarchical /// <summary> /// SetHierarchical /// </summary> /// <param name="bExpanded"></param> private void SetHierarchical(bool bExpanded) { int iCount; try { for (iCount = 0;iCount <= dgValues.Items.Count - 1;iCount++) { //set the bg colour of the Customer and Order Rows and the plus minus cells
if (dgValues.Items[iCount].Cells[1].Text != " ") { dgValues.Items[iCount].BackColor = System.Drawing.Color.Wheat; dgValues.Items[iCount].Cells[0].BackColor = System.Drawing.Color.Tan; } if (dgValues.Items[iCount].Cells[3].Text != " ") { dgValues.Items[iCount].BackColor = System.Drawing.Color.AntiqueWhite; dgValues.Items[iCount].Cells[2].BackColor = System.Drawing.Color.Tan; } //set the bg colour of the total rows if (dgValues.Items[iCount].Cells[4].Text == "Customer Total") { dgValues.Items[iCount].BackColor = System.Drawing.Color.AntiqueWhite; }
if (bExpanded) { //hide + on all rows where there is not an expandable node if (dgValues.Items[iCount].Cells[3].Text == " ") { dgValues.Items[iCount].Cells[2].Controls[0].Visible = false; } else { //set the minus sign ((LinkButton)dgValues.Items[iCount].Cells[2].Controls[0]).Text = "-"; ((LinkButton)dgValues.Items[iCount].Cells[2].Controls[0]).CssClass = "PlusMinus"; } //hide + on all Coustomer rows where there is not an expandable node if (dgValues.Items[iCount].Cells[1].Text == " ") { dgValues.Items[iCount].Cells[0].Controls[0].Visible = false; } else { //set the minus sign ((LinkButton)dgValues.Items[iCount].Cells[0].Controls[0]).Text = "-"; } } } } catch (Exception x) { CommonFunctions.pLogError(x, ConfigurationSettings.AppSettings["errorLog"], "DefaultPage.SetHierarchical",true); CommonFunctions.pShowError(x.Message, Page, tblErrors); } } #endregion #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dgValues.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgValues_ItemCommand); this.Load += new System.EventHandler(this.Page_Load);} #endregion /// ///////////////////////////////////////////////////////////////////////////////////////////////////// #region dgValues_ItemCommand private void dgValues_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { int iCount = e.Item.ItemIndex + 1; try { if (e.CommandName == "ExpandOrder") { if (((LinkButton)e.Item.Cells[2].Controls[0]).Text == "-") { do { dgValues.Items[iCount].Visible = false; iCount += 1; if (iCount >= dgValues.Items.Count) { break; } } while(dgValues.Items[iCount].Cells[3].Text == " " && dgValues.Items[iCount].Cells[1].Text == " "); //change the minus to a plus ((LinkButton)e.Item.Cells[2].Controls[0]).Text = "+"; } else { //Show all child rows in the node do { dgValues.Items[iCount].Visible = true; iCount += 1; if (iCount >= dgValues.Items.Count) { break; } } while(dgValues.Items[iCount].Cells[3].Text == " "); //change the plus to a minus ((LinkButton)e.Item.Cells[2].Controls[0]).Text = "-"; } } else { if(e.CommandName == "ExpandCustomer") { if (((LinkButton)e.Item.Cells[0].Controls[0]).Text == "-") { do { dgValues.Items[iCount].Visible = false; //if this is an order row set the plus sign as we are collapsing it too if (dgValues.Items[iCount].Cells[3].Text != " ") { ((LinkButton)dgValues.Items[iCount].Cells[2].Controls[0]).Text = "+"; } iCount += 1; if (iCount >= dgValues.Items.Count) { break; } } while(dgValues.Items[iCount].Cells[1].Text == " "); //hide the total row dgValues.Items[iCount - 1].Visible = false; //change the minus to a plus ((LinkButton)e.Item.Cells[0].Controls[0]).Text = "+"; } else { do { //Show all Order rows in the node if (dgValues.Items[iCount].Cells[3].Text != " ") { dgValues.Items[iCount].Visible = true; } iCount += 1; if (iCount >= dgValues.Items.Count) { break; } } while (dgValues.Items[iCount].Cells[1].Text == " "); //change the plus to a minus dgValues.Items[iCount - 1].Visible = true; ((LinkButton)e.Item.Cells[0].Controls[0]).Text = "-"; } } } } catch (Exception x) { CommonFunctions.pLogError(x, ConfigurationSettings.AppSettings["errorLog"], "DefaultPage.dgValuesItemCommand",true); CommonFunctions.pShowError(x.Message, Page, tblErrors); } } #endregion #region cmdHome_Click /// <summary> /// Home Button Link /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmdHome_Click(object sender, System.Web.UI.ImageClickEventArgs e) { Response.Redirect("http://www.sonar.ca"); } #endregion cmdHome_Click
aspx:
<%@ Page language="c#" Codebehind="Default.aspx.cs" AutoEventWireup="false" Inherits="DataGridTestCS._Default" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Default</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<FONT face="宋体">
<asp:label id="lblLoading" style="Z-INDEX: 101; LEFT: 12px; POSITION: absolute; TOP: 8px" runat="server"
Width="220px">Loading..............</asp:label></FONT>
<TABLE id="tblErrors" style="HEIGHT: 86px" cellSpacing="0" cellPadding="0" width="700"
align="center" border="0" runat="server">
<TR>
<TD style="WIDTH: 81px" align="center" bgColor="#003163"><IMG src="Images/error.gif">
</TD>
<TD vAlign="top" align="left" bgColor="#003163">
<asp:validationsummary id="vsErrors" runat="server" Width="541px" CssClass="ErrorBlock" BackColor="#003163"
ForeColor=" " Height="73px" HeaderText="Houston we have a problem..."></asp:validationsummary><asp:customvalidator id="cvError" runat="server" Width="51px" Visible="False"></asp:customvalidator></TD>
</TR>
<TR>
<TD style="WIDTH: 81px" align="center"></TD>
<TD vAlign="top" align="left"> </TD>
</TR>
</TABLE>
<TABLE id="tblResults" cellSpacing="0" cellPadding="2" width="700" align="center" border="0"
runat="server">
<TR>
<TD style="HEIGHT: 32px" vAlign="middle" bgColor="#003163" colSpan="3">
<DIV id="lblResults" style="DISPLAY: inline; FONT-WEIGHT: bold; FONT-SIZE: 10pt; WIDTH: 300px; COLOR: white; FONT-FAMILY: verdana; HEIGHT: 18px"
runat="server" ms_positioning="FlowLayout"> Northwind Orders
By Customer</DIV>
</TD>
<td bgColor="#003163" align="right" style="HEIGHT: 32px" vAlign="middle">
<asp:ImageButton id="cmdHome" runat="server" BorderColor="SteelBlue" BorderWidth="2px" BorderStyle="Outset"
ImageUrl="Images/home.gif" ImageAlign="Middle"></asp:ImageButton>
</td>
</TR>
<TR>
<TD style="WIDTH: 176px" align="center" colSpan="4"><BR>
<asp:datagrid id="dgValues" runat="server" Width="694px" BackColor="White" PageSize="20" BorderStyle="None"
BorderWidth="1px" BorderColor="#07376F" CellPadding="4" AutoGenerateColumns="False">
<SelectedItemStyle Font-Bold="True" ForeColor="#CCFF99" BackColor="#009999"></SelectedItemStyle>
<EditItemStyle Font-Size="XX-Small" Font-Names="Verdana" ForeColor="DarkBlue"></EditItemStyle>
<AlternatingItemStyle Font-Size="XX-Small" Font-Names="Verdana" ForeColor="DarkBlue" BackColor="AliceBlue"></AlternatingItemStyle>
<ItemStyle Font-Size="XX-Small" Font-Names="Verdana" Height="20px" ForeColor="DarkBlue" BackColor="White"></ItemStyle>
<HeaderStyle Font-Size="XX-Small" Font-Names="Verdana" Font-Bold="True" ForeColor="White" BackColor="#003163"></HeaderStyle>
<FooterStyle ForeColor="White" BackColor="#07376F"></FooterStyle>
<Columns>
<asp:ButtonColumn Text="-" CommandName="ExpandCustomer">
<HeaderStyle Width="10px"></HeaderStyle>
</asp:ButtonColumn>
<asp:BoundColumn DataField="CompanyName" ReadOnly="True" HeaderText="Customer"></asp:BoundColumn>
<asp:ButtonColumn Text="-" CommandName="ExpandOrder">
<HeaderStyle Width="10px"></HeaderStyle>
</asp:ButtonColumn>
<asp:BoundColumn DataField="OrderDate" HeaderText="Order Date" DataFormatString="{0:dd-MMM-yyyy}">
<ItemStyle Wrap="False"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="ProductName" HeaderText="Product"></asp:BoundColumn>
<asp:BoundColumn DataField="Quantity" HeaderText="Quantity">
<ItemStyle Wrap="False"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="UnitPrice" HeaderText="Unit Price" DataFormatString="{0:C}">
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="Total" HeaderText="Total" DataFormatString="{0:C}"></asp:BoundColumn>
</Columns>
<PagerStyle NextPageText=" Next &gt;" Font-Size="XX-Small" Font-Names="Verdana" Font-Bold="True"
PrevPageText="&lt; Previous" HorizontalAlign="Left" ForeColor="White" BackColor="#07376F"></PagerStyle>
</asp:datagrid></TD>
</TR>
<TR>
<TD style="WIDTH: 135px"></TD>
<TD style="WIDTH: 257px"></TD>
<TD style="WIDTH: 120px"></TD>
<TD align="right"></TD>
</TR>
</TABLE>
</form>
</body>
</HTML>
/// <summary>
/// Page_load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Page_Load(object sender, System.EventArgs e)
{
try
{
tblErrors.Visible = false; if (!Page.IsPostBack)
{
if (moConn.State != ConnectionState.Open)
{
moConn.ConnectionString ="server=10.99.15.245;database=Northwind;user id=sa";// ConfigurationSettings.AppSettings["connectionString"];
moConn.Open();
} LoadResults(); }
}
catch (Exception x)
{
CommonFunctions.pLogError(x, ConfigurationSettings.AppSettings["errorLog"], "DefaultPage.PageLoad", true);
CommonFunctions.pShowError(x.Message, Page, tblErrors);
}
}
#endregion #region ClosePage
/// <summary>
/// ClosePage
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ClosePage(object sender, System.EventArgs e)
{
if (moConn.State == ConnectionState.Open)
{
moConn.Close();
}
}
#endregion
/// <summary>
/// LoadResults
/// </summary>
private void LoadResults()
{
DataRow oRow;
DataTable oTable = new DataTable("RESULTS");
string sSQL;
SqlDataAdapter oDA = new SqlDataAdapter();
DataSet oDS = new DataSet(); try
{
//set up columns in the results table
oTable.Columns.Add("CompanyName",Type.GetType("System.String"));
oTable.Columns.Add("OrderDate",Type.GetType("System.DateTime"));
oTable.Columns.Add("ProductName",Type.GetType("System.String"));
oTable.Columns.Add("Quantity",Type.GetType("System.Int32"));
oTable.Columns.Add("UnitPrice",Type.GetType("System.Decimal"));
oTable.Columns.Add("Total",Type.GetType("System.Decimal")); //send a batch of selects as the data adapters SelectCommand
sSQL = "SELECT * FROM CUSTOMERS WHERE CompanyName < 'C'" + " SELECT * FROM ORDERS WHERE CustomerID < 'C'" + " SELECT [ORDER DETAILS].OrderId, [ORDER DETAILS].Quantity, [ORDER DETAILS].UnitPrice, ProductName FROM [ORDER DETAILS], PRODUCTS WHERE [ORDER DETAILS].ProductId = PRODUCTS.ProductId"; oDA = new SqlDataAdapter(sSQL, moConn); //map the tables that are returned from the DB to the ones we will create in the dataset
oDA.TableMappings.Add("Customers", "Customers");
oDA.TableMappings.Add("Customers1", "Orders");
oDA.TableMappings.Add("Customers2", "Details"); oDA.Fill(oDS, "Customers"); //set up the relationships
oDS.Relations.Add("Customer_Order", oDS.Tables["Customers"].Columns["CustomerID"], oDS.Tables["Orders"].Columns["CustomerID"]);
oDS.Relations.Add("Order_Detail", oDS.Tables["Orders"].Columns["OrderId"], oDS.Tables["Details"].Columns["OrderId"], false); //loop through the tables getting child rows as necessary
foreach (DataRow oCustomerRow in oDS.Tables["Customers"].Rows)
{
decimal dOrderTotal = 0;
oRow = oTable.NewRow();
oRow["CompanyName"] = oCustomerRow["CompanyName"];
oTable.Rows.Add(oRow); foreach (DataRow oOrderRow in oCustomerRow.GetChildRows("Customer_Order"))
{
oRow = oTable.NewRow();
oRow["OrderDate"] = oOrderRow["OrderDate"];
oTable.Rows.Add(oRow); foreach (DataRow oDetailRow in oOrderRow.GetChildRows("Order_Detail"))
{
oRow = oTable.NewRow();
oRow["ProductName"] = oDetailRow["ProductName"];
oRow["Quantity"] = oDetailRow["Quantity"];
oRow["UnitPrice"] = oDetailRow["UnitPrice"];
//calculate on the fly oRow["Total"] = (Convert.ToDecimal(oDetailRow["UnitPrice"]) * Convert.ToDecimal(oDetailRow["Quantity"]));
oTable.Rows.Add(oRow); //add to running total
dOrderTotal += Convert.ToDecimal(oRow["Total"]);
}
}
oRow = oTable.NewRow();
oRow["ProductName"] = "Customer Total";
oRow["Total"] = dOrderTotal;
oTable.Rows.Add(oRow);
} dgValues.DataSource = oTable;
dgValues.DataBind(); SetHierarchical(false);
} catch (Exception x)
{
CommonFunctions.pLogError(x, ConfigurationSettings.AppSettings["errorLog"], "DefaultPage.LoadResults",true);
CommonFunctions.pShowError(x.Message, Page, tblErrors);
}
}
#endregion
/// <summary>
/// SetHierarchical
/// </summary>
/// <param name="bExpanded"></param>
private void SetHierarchical(bool bExpanded)
{
int iCount; try
{
for (iCount = 0;iCount <= dgValues.Items.Count - 1;iCount++)
{
//set the bg colour of the Customer and Order Rows and the plus minus cells
if (dgValues.Items[iCount].Cells[1].Text != " ")
{
dgValues.Items[iCount].BackColor = System.Drawing.Color.Wheat;
dgValues.Items[iCount].Cells[0].BackColor = System.Drawing.Color.Tan;
} if (dgValues.Items[iCount].Cells[3].Text != " ")
{
dgValues.Items[iCount].BackColor = System.Drawing.Color.AntiqueWhite;
dgValues.Items[iCount].Cells[2].BackColor = System.Drawing.Color.Tan;
} //set the bg colour of the total rows
if (dgValues.Items[iCount].Cells[4].Text == "Customer Total")
{
dgValues.Items[iCount].BackColor = System.Drawing.Color.AntiqueWhite;
}
if (bExpanded)
{
//hide + on all rows where there is not an expandable node
if (dgValues.Items[iCount].Cells[3].Text == " ")
{
dgValues.Items[iCount].Cells[2].Controls[0].Visible = false;
}
else
{
//set the minus sign
((LinkButton)dgValues.Items[iCount].Cells[2].Controls[0]).Text = "-";
((LinkButton)dgValues.Items[iCount].Cells[2].Controls[0]).CssClass = "PlusMinus";
} //hide + on all Coustomer rows where there is not an expandable node
if (dgValues.Items[iCount].Cells[1].Text == " ")
{
dgValues.Items[iCount].Cells[0].Controls[0].Visible = false;
}
else
{
//set the minus sign
((LinkButton)dgValues.Items[iCount].Cells[0].Controls[0]).Text = "-";
}
} }
} catch (Exception x)
{
CommonFunctions.pLogError(x, ConfigurationSettings.AppSettings["errorLog"], "DefaultPage.SetHierarchical",true);
CommonFunctions.pShowError(x.Message, Page, tblErrors);
}
}
#endregion #region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
} /// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dgValues.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgValues_ItemCommand);
this.Load += new System.EventHandler(this.Page_Load);}
#endregion
/// /////////////////////////////////////////////////////////////////////////////////////////////////////
#region dgValues_ItemCommand
private void dgValues_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{ int iCount = e.Item.ItemIndex + 1; try
{
if (e.CommandName == "ExpandOrder")
{
if (((LinkButton)e.Item.Cells[2].Controls[0]).Text == "-")
{
do
{
dgValues.Items[iCount].Visible = false;
iCount += 1;
if (iCount >= dgValues.Items.Count)
{
break;
}
}
while(dgValues.Items[iCount].Cells[3].Text == " " && dgValues.Items[iCount].Cells[1].Text == " ");
//change the minus to a plus
((LinkButton)e.Item.Cells[2].Controls[0]).Text = "+";
}
else
{
//Show all child rows in the node
do
{
dgValues.Items[iCount].Visible = true;
iCount += 1;
if (iCount >= dgValues.Items.Count)
{
break;
}
}
while(dgValues.Items[iCount].Cells[3].Text == " ");
//change the plus to a minus
((LinkButton)e.Item.Cells[2].Controls[0]).Text = "-";
}
}
else
{
if(e.CommandName == "ExpandCustomer")
{
if (((LinkButton)e.Item.Cells[0].Controls[0]).Text == "-")
{
do
{
dgValues.Items[iCount].Visible = false;
//if this is an order row set the plus sign as we are collapsing it too
if (dgValues.Items[iCount].Cells[3].Text != " ")
{
((LinkButton)dgValues.Items[iCount].Cells[2].Controls[0]).Text = "+";
}
iCount += 1;
if (iCount >= dgValues.Items.Count)
{
break;
}
}
while(dgValues.Items[iCount].Cells[1].Text == " ");
//hide the total row
dgValues.Items[iCount - 1].Visible = false;
//change the minus to a plus
((LinkButton)e.Item.Cells[0].Controls[0]).Text = "+";
}
else
{
do
{ //Show all Order rows in the node
if (dgValues.Items[iCount].Cells[3].Text != " ")
{
dgValues.Items[iCount].Visible = true;
}
iCount += 1;
if (iCount >= dgValues.Items.Count)
{
break;
} }
while (dgValues.Items[iCount].Cells[1].Text == " ");
//change the plus to a minus
dgValues.Items[iCount - 1].Visible = true;
((LinkButton)e.Item.Cells[0].Controls[0]).Text = "-";
}
}
}
}
catch (Exception x)
{
CommonFunctions.pLogError(x, ConfigurationSettings.AppSettings["errorLog"], "DefaultPage.dgValuesItemCommand",true);
CommonFunctions.pShowError(x.Message, Page, tblErrors);
}
}
#endregion #region cmdHome_Click
/// <summary>
/// Home Button Link
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cmdHome_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
Response.Redirect("http://www.sonar.ca");
}
#endregion cmdHome_Click