Trying To Display Average by Dividing Each Column by the Sum of the Same Column in a GridView with ASP.Net

Viewed 73

I need to display the average of clicks in a percentage inside a Gridview I already formatted to show the Index and Clicks. I need to divide the number in each "Clicks" column by the sum of the same "Clicks" column.

Index   Clicks   %
       
| 1 |  | 24 | | 44% |          
| 2 |  | 31 | | 56% | 

Here is my GridView

<asp:Table ID="Table2" runat="server">
    <asp:TableRow>
        <asp:TableCell>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
                   <Columns>
                       <asp:BoundField DataField="Index" HeaderText="Index" SortExpression="Index"></asp:BoundField>
                       <asp:BoundField DataField="Clicks" HeaderText="Clicks" ReadOnly="True" SortExpression="Clicks"></asp:BoundField>
                     
                   </Columns>
               </asp:GridView>
               
               <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:trackingstatsConnectionString %>' SelectCommand="SELECT LinkId as 'Index', count(*) as Clicks FROM Track_Click_7 where CampaignId = 18444 Group by LinkId;"></asp:SqlDataSource>
           </asp:TableCell>
       </asp:TableRow>
   </asp:Table>

   
2 Answers
SELECT DISTINCT
    LinkId [Index],
    Count(*) over (Partition by LinkId) [Clicks],
    Convert(VARCHAR(10), count(*) over (Partition by LinkId) * 100 / count(*) over (Partition by 1)) + '%' [Percent]
FROM
    Track_Click_7
WHERE
    CampaignId = 18444

I would start by trying to solve in the SQL Statement, like above.. Probably not the best solution though, but an idea.

You can do this quite a few different ways.

but, easy way?

Simple declare a PUBLIC var at the page class level, and then use that as a expression in the markup.

So, your typical code to load a grid will look like this:

    public double TotalClicks = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {
        // load up our grid
        using (SqlCommand cmdSQL = new SqlCommand("SELECT TOP 15 * from tblHotels ORDER BY HotelName ",
            new SqlConnection(Properties.Settings.Default.TEST4)))
        {
            cmdSQL.Connection.Open();
            DataTable rst = new DataTable();
            rst.Load(cmdSQL.ExecuteReader());
            TotalClicks = Convert.ToDouble(rst.Compute("SUM(Clicks)", ""));
            GridView1.DataSource = rst;
            GridView1.DataBind();
        }
    }

So, now when you load the table, just total that column - set to a public var for that page.

Now, you can simple display the % in the grid markup like this:

<asp:TemplateField HeaderText ="%">
  <ItemTemplate>
   <asp:Label ID="MyPercent" runat="server" 
    Text = '<%#  String.Format("{0:P2}.", (Convert.ToDouble(Eval("Clicks")) / TotalClicks )) %>'   >
   </asp:Label>
  </ItemTemplate>
</asp:TemplateField>

So total grid markup looks like this:

<asp:GridView ID="GridView1" runat="server" CssClass="table table-hover" 
    AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" >

    <Columns>
        <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
        <asp:BoundField DataField="LastName" HeaderText="LastName" />
        <asp:BoundField DataField="HotelName" HeaderText="HotelName"  />
        <asp:BoundField DataField="Province" HeaderText="Province" />
        <asp:BoundField DataField="Clicks" HeaderText="Clicks"  />

        <asp:TemplateField HeaderText ="%">
            <ItemTemplate>
                <asp:Label ID="MyPercent" runat="server" 
                    Text = '<%#  String.Format("{0:P2}.", (Convert.ToDouble(Eval("Clicks")) / TotalClicks )) %>'   >
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Output: enter image description here

Related