Click here to Skip to main content
15,889,335 members
Home / Discussions / C#
   

C#

 
AnswerRe: Methods of a collection class are not always called Pin
Luc Pattyn12-Mar-12 4:23
sitebuilderLuc Pattyn12-Mar-12 4:23 
GeneralRe: Methods of a collection class are not always called Pin
CDP180212-Mar-12 21:21
CDP180212-Mar-12 21:21 
AnswerRe: Methods of a collection class are not always called Pin
Pete O'Hanlon11-Mar-12 20:01
mvePete O'Hanlon11-Mar-12 20:01 
GeneralRe: Methods of a collection class are not always called Pin
CDP180212-Mar-12 0:07
CDP180212-Mar-12 0:07 
GeneralRe: Methods of a collection class are not always called Pin
Pete O'Hanlon12-Mar-12 0:43
mvePete O'Hanlon12-Mar-12 0:43 
AnswerRe: Methods of a collection class are not always called Pin
Bernhard Hiller11-Mar-12 21:18
Bernhard Hiller11-Mar-12 21:18 
GeneralRe: Methods of a collection class are not always called Pin
CDP180212-Mar-12 0:27
CDP180212-Mar-12 0:27 
QuestionExport to Excel - DropDownList Pin
Andrew Woodward11-Mar-12 10:12
Andrew Woodward11-Mar-12 10:12 
Hi,

I have a gridview that is exported to Excel using C#.
This all works great. The GridView is populated after selecting from a dropdownlist to filter the results.
I would like to add a title to the worksheet so users know what the results refer to. I would like to use the value of the dropdownlist. Is this possible.

My code is
ASP.NET
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/MasterPage.master" AutoEventWireup="true" CodeFile="TeamVolumeSplitQ32011.aspx.cs" Inherits="Printing_Team_Usage_TeamVolumeSplit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="TeamNameSrc" 
        DataTextField="LongName" DataValueField="LedgerID" 
        AppendDataBoundItems="True" AutoPostBack="True">
        <asp:ListItem Value = "">Please Make a Selection</asp:ListItem>
    </asp:DropDownList>
    <asp:SqlDataSource ID="TeamNameSrc" runat="server" 
        ConnectionString="<%$ ConnectionStrings:Docupro_ReportingConnectionString %>" 
        SelectCommand="SELECT [LedgerID], [LongName] FROM [tblLedger]">
    </asp:SqlDataSource>
    <br />
    <br />
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AllowSorting="True" AutoGenerateColumns="False" BackColor="White" 
        BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" 
        DataSourceID="TeamVolumeSrc" ForeColor="Black" GridLines="Vertical" 
        ShowFooter="True" 
        EmptyDataText="There are no records to display" 
        onrowdatabound="GridView1_RowDataBound">
        <PagerSettings Mode="NextPreviousFirstLast" NextPageText="Next" 
            PreviousPageText="Prev" />
        <RowStyle BackColor="#F7F7DE" />
        <Columns>
            <asp:TemplateField HeaderText="User" SortExpression="User">
                <EditItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("User") %>'></asp:Label>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lblUser" runat="server" Font-Bold="True" Text="Totals"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("User") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Colour" SortExpression="Colour">
                <EditItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Eval("Colour", "{0:#,0}") %>'></asp:Label>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lblTotalColour" runat="server" Font-Bold="True" Text="Label"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("Colour", "{0:#,0}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="B&W" SortExpression="B&W">
                <EditItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Eval("[B&W]", "{0:#,0}") %>'></asp:Label>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lblTotalBW" runat="server" Font-Bold="True" Text="Label"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("[B&W]", "{0:#,0}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Total Clicks" SortExpression="Total">
                <EditItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Eval("[Total Clicks]", "{0:#,0}") %>'></asp:Label>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lblTotalClicks" runat="server" Font-Bold="True" Text="Label"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("[Total Clicks]", "{0:#,0}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#CCCC99" />
        <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
        <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
    <asp:SqlDataSource ID="TeamVolumeSrc" runat="server" 
        
        
        ConnectionString="<%$ ConnectionStrings:Docupro_ReportingConnectionString %>" SelectCommand="USE Docupro_Reporting
select
	T5.DisplayName AS 'User',
	0+COALESCE(SUM(CASE
		WHEN T2.LongName LIKE '%Colour%' THEN T1.Quantity
	END),0)AS Colour,
	0+COALESCE(SUM(CASE
		WHEN T2.LongName LIKE '%B&W%' THEN T1.Quantity
	END),0)AS 'B&W',
 SUM(T1.Quantity) AS 'Total Clicks'
FROM tblTransaction T1
JOIN tblItem T2 ON T1.ItemID = T2.ItemID
JOIN tblLedger T3 ON T1.LedgerID = T3.LedgerID
JOIN tblTender T4 ON T1.TenderID = T4.TenderID
JOIN tblCustomer T5 ON T4.CustomerID = T5.CustomerID
WHERE (TransactionDateTime BETWEEN '2011-10-01' AND '2012-01-01')
AND 
(T2.LongName <> 'Scan 2' AND T2.LongName <> 'Scan 1')
AND T3.LedgerID = @LedgerID
GROUP BY
	T5.DisplayName
ORDER BY T5.DisplayName">
<SelectParameters>
    <asp:ControlParameter ControlID="DropDownList1" Name="LedgerID" 
        PropertyName="SelectedValue" Type="Int32" />
                
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<asp:Button ID="btnExcelExport" runat="server" Text="Export To Excel" 
        onclick="btnExcelExport_Click" />
<br />Paging Enabled?
<asp:RadioButtonList ID="rbPaging" runat="server">
<asp:ListItem  Text = "Yes" Value = "True" Selected = "True">
</asp:ListItem>
<asp:ListItem  Text = "No" Value = "False"></asp:ListItem>
</asp:RadioButtonList>
<br />
</asp:Content>


Code behind is
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Configuration;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
public partial class Printing_Team_Usage_TeamVolumeSplit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    int totalColour = 0;
    int totalBW = 0;
    int totalClicks = 0;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            totalColour += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Colour"));
            totalBW += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "B&W"));
            totalClicks += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Total clicks"));
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblColour = (Label)e.Row.FindControl("lblTotalColour");
            Label lblBW = (Label)e.Row.FindControl("lblTotalBW");
            Label lblClicks = (Label)e.Row.FindControl("lblTotalClicks");
            lblColour.Text = totalColour.ToString("#,#");
            lblBW.Text = totalBW.ToString("#,#");
            lblClicks.Text = totalClicks.ToString("#,#");
        }
    }
    protected void btnExcelExport_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition",
            "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        PrepareForExport(GridView1);
 //       PrepareForExport(GridView2);
        Table tb = new Table();
        TableRow tr1 = new TableRow();
        TableCell cell1 = new TableCell();
        cell1.Controls.Add(GridView1);
        tr1.Cells.Add(cell1);
  //      TableCell cell3 = new TableCell();
  //      cell3.Controls.Add(GridView2);
        TableCell cell2 = new TableCell();
        cell2.Text = " ";
  //      if (rbPreference.SelectedValue == "2")
  //      {
  //          tr1.Cells.Add(cell2);
  //         tr1.Cells.Add(cell3);
  //          tb.Rows.Add(tr1);
  //      }
  //      else
  //      {
            TableRow tr2 = new TableRow();
            tr2.Cells.Add(cell2);
            TableRow tr3 = new TableRow();
  //          tr3.Cells.Add(cell3);
            tb.Rows.Add(tr1);
            tb.Rows.Add(tr2);
            tb.Rows.Add(tr3);
  //      }
        ClearControls(GridView1);
   //     ClearControls(GridView2);
        tb.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style>.textmode{mso-number-format:\@;}</style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
    protected void PrepareForExport(GridView Gridview)
    {
        Gridview.AllowPaging = Convert.ToBoolean(rbPaging.SelectedItem.Value);
        Gridview.DataBind();
        //Change the Header Row back to white color
        Gridview.HeaderRow.Style.Add("background-color", "#FFFFFF");
        //Apply style to Individual Cells
        for (int k = 0; k < Gridview.HeaderRow.Cells.Count; k++)
        {
            Gridview.HeaderRow.Cells[k].Style.Add("background-color", "green");
        }

        for (int i = 0; i < Gridview.Rows.Count; i++)
        {
            GridViewRow row = Gridview.Rows[i];
            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;
            //Apply text style to each Row
            row.Attributes.Add("class", "number");
            //Apply style to Individual Cells of Alternating Row
            if (i % 2 != 0)
            {
                for (int j = 0; j < Gridview.Rows[i].Cells.Count; j++)
                {
                    row.Cells[j].Style.Add("background-color", "#C2D69B");
                }
            }
        }
    }
    private void ClearControls(Control control)
    {
        for (int i = control.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(control.Controls[i]);
        }
        if (!(control is TableCell))
        {
            if (control.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                try
                {
                    literal.Text =
                        (string)control.GetType().GetProperty("SelectedItem").
                            GetValue(control, null);
                }
                catch
                { }
                control.Parent.Controls.Remove(control);
            }
            else if (control.GetType().GetProperty("Text") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                literal.Text =
                    (string)control.GetType().GetProperty("Text").
                        GetValue(control, null);
                control.Parent.Controls.Remove(control);
            }
        }
        return;
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //   base.VerifyRenderingInServerForm(control);
    }
    
}


Many thanks
Andy

Questioninsert image in datagrid Pin
MemberDotNetting11-Mar-12 9:06
MemberDotNetting11-Mar-12 9:06 
AnswerRe: insert image in datagrid Pin
OriginalGriff11-Mar-12 9:41
mveOriginalGriff11-Mar-12 9:41 
GeneralRe: insert image in datagrid Pin
MemberDotNetting12-Mar-12 7:09
MemberDotNetting12-Mar-12 7:09 
Questioncombobox Pin
MemberDotNetting11-Mar-12 4:42
MemberDotNetting11-Mar-12 4:42 
AnswerRe: combobox Pin
Ravi Bhavnani11-Mar-12 5:12
professionalRavi Bhavnani11-Mar-12 5:12 
GeneralRe: combobox Pin
MemberDotNetting11-Mar-12 5:45
MemberDotNetting11-Mar-12 5:45 
GeneralRe: combobox Pin
OriginalGriff11-Mar-12 6:17
mveOriginalGriff11-Mar-12 6:17 
GeneralRe: combobox Pin
MemberDotNetting11-Mar-12 6:29
MemberDotNetting11-Mar-12 6:29 
GeneralRe: combobox Pin
OriginalGriff11-Mar-12 6:51
mveOriginalGriff11-Mar-12 6:51 
GeneralRe: combobox Pin
MemberDotNetting11-Mar-12 6:59
MemberDotNetting11-Mar-12 6:59 
AnswerRe: combobox Pin
OriginalGriff11-Mar-12 5:12
mveOriginalGriff11-Mar-12 5:12 
GeneralRe: combobox Pin
Ravi Bhavnani11-Mar-12 5:14
professionalRavi Bhavnani11-Mar-12 5:14 
GeneralRe: combobox Pin
OriginalGriff11-Mar-12 5:21
mveOriginalGriff11-Mar-12 5:21 
GeneralRe: combobox Pin
MemberDotNetting11-Mar-12 5:43
MemberDotNetting11-Mar-12 5:43 
GeneralRe: combobox Pin
OriginalGriff11-Mar-12 5:52
mveOriginalGriff11-Mar-12 5:52 
GeneralRe: combobox Pin
MemberDotNetting11-Mar-12 6:03
MemberDotNetting11-Mar-12 6:03 
GeneralRe: combobox Pin
OriginalGriff11-Mar-12 6:14
mveOriginalGriff11-Mar-12 6:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.