Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

GridView CheckBox & Footer Total Problem...

Options
  • 18-06-2012 1:26am
    #1
    Closed Accounts Posts: 3,912 ✭✭✭


    Hi Folks,

    I have a GridView which works fine & in my GridView I have a few column totals in my GridView Footer which all works fine...

    I've recently changed my code to add a column of Checkboxes into my GridView, again, all grand there, so probs...

    But what I need to do is when a CheckBox is ticked or unticked, I need the SUM values in the Footer to change accordingly.

    My problem is that I'm using the event handler for the Checkbox to do this, but I don't seem to be able to access/reference the label in my GridView footer...

    Here's my aspx code:

    [PHP]
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" GridLines="None"
    AutoGenerateEditButton="false" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="GridView1_RowDataBound"
    DataKeyNames="ID" DataSourceID="SqlDataSource1" BorderStyle="Dashed" BorderColor="SlateGray" BorderWidth="1" HeaderStyle-Font-Size="smaller"
    Width="970px" style="margin-right: 7px" PageSize="30">

    <RowStyle BorderStyle="None" HorizontalAlign="Center" VerticalAlign="Middle" Font-Size="Smaller" Font-Strikeout="False" Height="24px" />

    <Columns>
    <asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
    <EditItemTemplate>
    <asp:Label ID="Label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
    </EditItemTemplate>
    <ItemTemplate>
    <asp:Label ID="Label5ID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="view" SortExpression="view">
    <ItemTemplate>
    <asp:CheckBox ID="CheckBox1" runat="server" Enabled="true" Checked="false" AutoPostBack="true" OnCheckedChanged="CheckBox1_OnCheckedChanged" />
    </ItemTemplate>
    </asp:TemplateField>


    <asp:TemplateField HeaderText="Owner" SortExpression="TransactionOwner">
    <EditItemTemplate>
    <asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource2" DataTextField="UserName" DataValueField="UserName" SelectedValue='<%# Bind("TransactionOwner") %>'>
    </asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate>
    <asp:Label ID="Label14" runat="server" Text='<%# Bind("TransactionOwner") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Status" ItemStyle-HorizontalAlign="Left" SortExpression="Status">
    <ItemTemplate>
    <b><asp:Label ID="Label2" runat="server" Text='<%# Bind("TransactionStatusFlag") %>'></asp:Label></b><br />
    <asp:Label ID="VehicleRegYearLabel" runat="server" Text='<%# Bind("VehicleRegYear") %>'></asp:Label>-<asp:Label ID="VehicleRegCountyLabel" runat="server" Text='<%# Bind("VehicleRegCounty") %>'></asp:Label>-<asp:Label ID="VehicleRegNumberLabel" runat="server" Text='<%# Bind("VehicleRegNumber") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Buy" SortExpression="PurchasePrice" ItemStyle-HorizontalAlign="Center">
    <ItemTemplate>
    <asp:Label ID="PurchasePriceLabel" runat="server" Text='<%# Bind("LinePrice", "{0:C}") %>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate><asp:Label ID="PurchasePriceLabelFooter" runat="server"></asp:Label></FooterTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Profit" SortExpression="TransactionProfit" ItemStyle-HorizontalAlign="Center">
    <ItemTemplate>
    <asp:Label ID="TransactionProfitLabel" runat="server" Text='<%# Bind("TransactionProfit", "{0:C}") %>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate><asp:Label ID="ProfitFooter" runat="server"></asp:Label></FooterTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Sell" SortExpression="Cost">
    <ItemTemplate>
    <span class="Apple-style-span" style="border-collapse: separate; color: rgb(0, 0, 0); font-family: 'Times New Roman'; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; word-spacing: 0px; -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; ">
    <span class="Apple-style-span" style="font-family: Verdana; text-align: justify;"></span></span><asp:Label ID="Label4" runat="server" Text='<%# Bind("Cost", "{0:C}") %>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate><asp:Label ID="TestFooter" runat="server"></asp:Label></FooterTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Client/Time" ItemStyle-HorizontalAlign="Left" SortExpression="Timestamp">
    <ItemTemplate>
    <b><asp:Label ID="CustomerNameLabel" runat="server" Text='<%# Bind("CustomerName") %>'></asp:Label></b><br />
    <asp:Label ID="Label11" runat="server" Text='<%# Bind("Timestamp") %>'></asp:Label><br />
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Make" SortExpression="Description" ItemStyle-HorizontalAlign="Left">
    <ItemTemplate>
    <b><asp:Label ID="Label5" runat="server" Text='<%# Bind("EngineSpec") %>'></asp:Label></b><br />
    <b><asp:Label ID="Label6" runat="server" Text='<%# Bind("Description") %>'></asp:Label></b><br />
    <asp:Label ID="Label9" runat="server" Text='<%# Bind("ProductType") %>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate><asp:Label ID="ProfitMarginLabelFooter" runat="server"></asp:Label>%</FooterTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Q" SortExpression="OrderCount">
    <ItemTemplate>
    <asp:Label ID="QuantityLabel" runat="server" Text='<%# Bind("Quantity") %>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate><asp:Label ID="QuantityFooter" runat="server"></asp:Label></FooterTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="VAT" SortExpression="OutputVATAmount">
    <ItemTemplate>
    <asp:Label ID="VATLabel" runat="server" Text='<%# Bind("OutputVATAmount", "{0:C}") %>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate><asp:Label ID="OutputVATAmountFooterLabel" runat="server"></asp:Label></FooterTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Total" SortExpression="LinePrice">
    <ItemTemplate>
    <asp:Label ID="LabelTotal" runat="server" Text='<%# Bind("InvoiceAmountDue", "{0:C}") %>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate><asp:Label ID="OrderTotalFooter" runat="server"></asp:Label></FooterTemplate>
    </asp:TemplateField>

    </Columns>
    <SelectedRowStyle BackColor="Lime" />
    <HeaderStyle BackColor="#FF3300" HorizontalAlign="Center" Height="16px" />
    <EditRowStyle BackColor="Lime" />
    <AlternatingRowStyle BackColor="#CCCCCC" BorderStyle="Dashed" BorderColor="OrangeRed" BorderWidth="1px" />
    <FooterStyle HorizontalAlign="Center" Font-Bold="true" BackColor="Silver" />

    </asp:GridView>
    [/PHP]

    And here's my Codebehind:

    [PHP]
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    //CheckBox Checkbox1 = (CheckBox)sender;
    //CheckBox Checkbox1 = (CheckBox)e.Row.FindControl("Checkbox1");
    //GridViewRow GridView1 = (GridViewRow)Checkbox1.NamingContainer;

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
    decimal rowTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "LinePrice"));
    grdTotal = grdTotal + rowTotal;

    int QuantTotal = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Quantity"));
    QuantityTotal = QuantityTotal + QuantTotal;

    decimal ProfTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "TransactionProfit"));
    TotalProfit = TotalProfit + ProfTotal;

    decimal BuyTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "LinePrice"));
    TotalBuy = TotalBuy + BuyTotal;

    decimal SellTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Cost"));
    TotalSell = TotalSell + SellTotal;

    decimal VATTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "OutputVATAmount"));
    TotalVAT = TotalVAT + VATTotal;

    decimal AmountTotal = decimal.Round(Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "InvoiceAmountDue")), 2);
    GridTotal = decimal.Round(GridTotal, 2) + decimal.Round(AmountTotal, 2);

    foreach (TableCell tCell in e.Row.Cells)
    {

    tCell.Style.Add("border-bottom", "1px Dashed #FF3300");

    tCell.Style.Add("border-left", "1px Dashed #FF3300");

    tCell.Style.Add("border-right", "1px Dashed #FF3300");
    }

    }
    if (e.Row.RowType == DataControlRowType.Footer)
    {
    Label lbl1 = (Label)e.Row.FindControl("OrderTotalFooter");
    lbl1.Text = GridTotal.ToString("c");

    Label lbl7 = (Label)e.Row.FindControl("OutputVATAmountFooterLabel");
    lbl7.Text = TotalVAT.ToString("c");

    Label lbl = (Label)e.Row.FindControl("TestFooter");
    lbl.Text = TotalSell.ToString("c");

    Label lbl2 = (Label)e.Row.FindControl("QuantityFooter");
    lbl2.Text = QuantityTotal.ToString();

    Label lbl3 = (Label)e.Row.FindControl("ProfitFooter");
    lbl3.Text = TotalProfit.ToString("c");

    Label lbl4 = (Label)e.Row.FindControl("PurchasePriceLabelFooter");
    lbl4.Text = TotalBuy.ToString("c");

    Label lbl6 = (Label)e.Row.FindControl("ProfitMarginLabelFooter");
    ProfitMargin = (TotalProfit / TotalBuy) * 100;
    lbl6.Text = ProfitMargin.ToString("F2");

    foreach (TableCell tCell in e.Row.Cells)
    {

    tCell.Style.Add("border-bottom", "1px Dashed #777");

    tCell.Style.Add("border-left", "1px Dashed #777");

    tCell.Style.Add("border-right", "1px Dashed #777");
    }


    }

    if (e.Row.RowType == DataControlRowType.Header)
    {
    foreach (TableCell tCell in e.Row.Cells)
    {

    tCell.Style.Add("border-bottom", "1px Dashed #888");

    tCell.Style.Add("border-left", "1px Dashed #888");

    tCell.Style.Add("border-right", "1px Dashed #888");
    }
    }


    }
    [/PHP]

    [PHP]
    protected void CheckBox1_OnCheckedChanged(object sender, EventArgs e)
    {

    CheckBox Checkbox1 = (CheckBox)sender;

    GridViewRow GridView1 = (GridViewRow)Checkbox1.NamingContainer;



    if (((CheckBox)GridView1.FindControl("Checkbox1")).Checked == true)
    {

    GridView1.BackColor = System.Drawing.Color.Lime;

    Label lb = (Label)GridView1.FindControl("VATLabel");
    Label lbtot = (Label)GridView1.FindControl("LabelTotal");


    lbtot.Text = lb.Text;


    }

    else
    {
    GridView1.BackColor = System.Drawing.Color.Transparent;
    Label lbtot = (Label)GridView1.FindControl("LabelTotal");

    lbtot.Text = "";

    }

    }
    [/PHP]

    Any help with this hugely appreciated, I've Googled it to death but I'm just not having any luck with a solution that will actually work for me... All this works fine & totals in the GridView Footer without Checkboxes, even with the Checkboxes, it works fine, but I can't get the sums in the footer labels to update when a checkbox is ticked or unticked, which is what I need to happen...

    My CheckBox event handler is firing and the data in one cell in each row is now changing, depending on whether the Checkbox is ticked/unticked, but for the life of me I can't work out how to update the label in my GridView footer!

    Thanks again for any help with this...

    HFC.


Comments

  • Registered Users Posts: 11,979 ✭✭✭✭Giblet


    How are you binding the GridView? You might need to add a if(!IsPostBack) around it.


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    Giblet wrote: »
    How are you binding the GridView? You might need to add a if(!IsPostBack) around it.

    Hi Giblet, thanks for the post...

    I just use the following SQLDataSource and each column is bound in the GridView template on the aspx page...

    [PHP]<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:xxxxxxxxConnectionString %>"
    SelectCommand="SELECT * FROM [Orders] WHERE (([PaymentStatus] = @PaymentStatus) AND ([TransactionStatus] = @TransactionStatus) AND [UserID] = @UserID) ORDER BY [ID] DESC"
    OldValuesParameterFormatString="original_{0}"
    onselecting="SqlDataSource1_Selecting">
    <SelectParameters>
    <asp:ControlParameter ControlID="DropDownList1" Name="PaymentStatus"
    PropertyName="SelectedValue" Type="String" />
    <asp:ControlParameter ControlID="DropDownList2" Name="TransactionStatus"
    PropertyName="SelectedValue" Type="String" />
    <asp:Parameter Name="UserID" Type="String" />
    </SelectParameters>
    </asp:SqlDataSource>[/PHP]

    I'm not really on strong ground with C#, I can code a bit but not really as proficient as I should be... What do you reckon I need to do with the if(!IsPostBack) thing you mentioned above?!?


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    I thought, now that I have my CheckBox working to make a cell blank where it previously had a decimal value in it, and those decimal values are all summing up in my GridView footer in a Label that I have in there, (this is all working fine btw), that the footer value would automatically update to reflect the sum of the cells in that column (all decimals), after one cell value had been removed due to the CheckBox having been ticked??!?... :confused::confused::confused:


  • Registered Users Posts: 11,979 ✭✭✭✭Giblet


    Do you call .Databind() on your gridview anywhere?


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    Giblet wrote: »
    Do you call .Databind() on your gridview anywhere?

    Ive just tried putting in a GridView1.Databind(); into the very end of my CheckBox event handler but it's not having any effect?!?

    [PHP]
    protected void CheckBox1_OnCheckedChanged(object sender, EventArgs e)
    {

    CheckBox Checkbox1 = (CheckBox)sender;

    GridViewRow GridView1 = (GridViewRow)Checkbox1.NamingContainer;



    if (((CheckBox)GridView1.FindControl("Checkbox1")).Checked == true)
    {

    GridView1.BackColor = System.Drawing.Color.Lime;

    Label lb = (Label)GridView1.FindControl("VATLabel");
    Label lbtot = (Label)GridView1.FindControl("LabelTotal");


    lbtot.Text = lb.Text;

    TotalVAT.ToString();

    }

    else
    {
    GridView1.BackColor = System.Drawing.Color.Transparent;
    Label lbtot = (Label)GridView1.FindControl("LabelTotal");

    lbtot.Text = "";


    }
    GridView1.DataBind();
    }
    [/PHP]


  • Advertisement
  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    If I try to be cute about it and put:
    [PHP]
    if (((CheckBox)GridView1.FindControl("Checkbox1")).Checked == true)

    [/PHP]
    into my GridView1_RowDataBound event handler, I get an error back saying that the CheckBox can't be found because this code:

    [PHP]
    CheckBox Checkbox1 = (CheckBox)sender;

    GridViewRow GridView1 = (GridViewRow)Checkbox1.NamingContainer;
    [/PHP]

    Will only run in the CheckBox event handler...

    So I'm lost for what to try to sort this out?!? :confused::confused::confused:


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    I've tried something like this as well but not having any luck with it...

    [PHP] protected void Update_OnClientClick(object sender, EventArgs e)
    {

    double sum = 0;
    foreach (GridViewRow gvr in GridView1.Rows)
    {
    CheckBox cb = (CheckBox)gvr.FindControl("CheckBox1");
    if (cb.Checked == true)
    {
    double amount = Convert.ToDouble(gvr.Cells[11].Text);
    sum += amount;
    GridView1.FooterRow.Cells[11].Text = sum.ToString();
    }

    if (cb.Checked == false)

    {
    double amount = Convert.ToDouble(gvr.Cells[11].Text);
    sum += amount;
    GridView1.FooterRow.Cells[11].Text = sum.ToString();

    }
    }

    }[/PHP]


  • Moderators, Science, Health & Environment Moderators Posts: 8,920 Mod ✭✭✭✭mewso


    I think you are on the right track re-binding the grid when a checkbox is checked and in the rowdatabound event do a null check or make sure you are accessing it in a datarow (the "if (e.Row.RowType == DataControlRowType.DataRow)" block).


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    mewso wrote: »
    I think you are on the right track re-binding the grid when a checkbox is checked and in the rowdatabound event do a null check or make sure you are accessing it in a datarow (the "if (e.Row.RowType == DataControlRowType.DataRow)" block).

    Hi Mewso, thanks for that. I just don't seem to be getting anywhere with this at all... Do folks think I'm right handling all this in the CheckBox1 event handler? I have this end of it working, I just can't get the footer label to update with the actual amounts in the column when I take a value out using the Checkbox being ticked...


  • Moderators, Science, Health & Environment Moderators Posts: 8,920 Mod ✭✭✭✭mewso


    No. Based on what you have I would do all the calculations in the databound event and have the checkchanged simply re-bind the grid. I stopped using the gridview a long time ago mind you and tend to use the repeater. I might approach this in a different way but considering what you have done so far I think re-binding and re-calculating each time is the easiest.


  • Advertisement
  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    mewso wrote: »
    No. Based on what you have I would do all the calculations in the databound event and have the checkchanged simply re-bind the grid. I stopped using the gridview a long time ago mind you and tend to use the repeater. I might approach this in a different way but considering what you have done so far I think re-binding and re-calculating each time is the easiest.

    It just doesn't seem to be working out at all for me? The only way I can get a part of it to work is to use the CheckBox event handler? If I try to use if statements to check whether the box is ticked or not, it won't work...


  • Moderators, Science, Health & Environment Moderators Posts: 8,920 Mod ✭✭✭✭mewso


    It just doesn't seem to be working out at all for me? The only way I can get a part of it to work is to use the CheckBox event handler? If I try to use if statements to check whether the box is ticked or not, it won't work...

    Have you included a check for null before accessing the checked property of the checkbox in the databound event?:-
    var chk = (CheckBox)GridView1.FindControl("Checkbox1");
    if (chk != null)    {
        if (chk.Checked == true)     {
        }
    }
    

    or shorter:-
    var chk = (CheckBox)GridView1.FindControl("Checkbox1");
    if (chk != null && chk.Checked)    {
    
    }
    

    You shouldn't need the null check if you are accessing it in the datarow part of your code (i.e. the checkbox will be null in the header and footer).


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    mewso wrote: »
    Have you included a check for null before accessing the checked property of the checkbox in the databound event?:-
    var chk = (CheckBox)GridView1.FindControl("Checkbox1");
    if (chk != null)    {
        if (chk.Checked == true)     {
        }
    }
    
    or shorter:-
    var chk = (CheckBox)GridView1.FindControl("Checkbox1");
    if (chk != null && chk.Checked)    {
    
    }
    
    You shouldn't need the null check if you are accessing it in the datarow part of your code (i.e. the checkbox will be null in the header and footer).

    I've just tried that but still no luck... I'm not getting any errors, but if I tick the CheckBox or untick it, it just does a PostBack but as per my code, the background colour of the row should change...

    [PHP]#region

    using System;
    using System.Collections.Generic;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using ShoppingCart.Business;
    using ShoppingCart.Common.Entities;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Data.Sql;
    using System.Data.SqlTypes;
    using System.Data;
    using System.Net.Mail;
    using System.Security.Cryptography;
    using System.Web.Security;
    using System.Web.SessionState;
    using System.Collections;
    using System.ComponentModel;
    using System.Text;

    #endregion

    namespace ShoppingCart.Web
    {
    public partial class TradeUnauthorisedTransactions : Page
    {

    decimal grdTotal = 0;
    int QuantityTotal = 0;
    decimal TotalBuy = 0;
    decimal TotalProfit = 0;
    decimal TotalSell = 0;
    decimal ProfitMargin = 0;
    decimal TotalVAT = 0;
    decimal GridTotal = 0;

    protected override void OnInit(EventArgs e)
    {

    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
    if (User.Identity.IsAuthenticated)
    {
    MembershipUser currentUser = Membership.GetUser();
    Guid currentUserId = (Guid)currentUser.ProviderUserKey;
    e.Command.Parameters["@userID&quot;].Value = currentUserId.ToString();


    }
    else
    {
    Label1.Text = string.Format("You need to be logged in to view the information on this page...");
    }

    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
    decimal rowTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "LinePrice"));
    grdTotal = grdTotal + rowTotal;

    int QuantTotal = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Quantity"));
    QuantityTotal = QuantityTotal + QuantTotal;

    decimal ProfTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "TransactionProfit"));
    TotalProfit = TotalProfit + ProfTotal;

    decimal BuyTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "LinePrice"));
    TotalBuy = TotalBuy + BuyTotal;

    decimal SellTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Cost"));
    TotalSell = TotalSell + SellTotal;

    decimal VATTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "OutputVATAmount"));
    TotalVAT = TotalVAT + VATTotal;

    decimal AmountTotal = decimal.Round(Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "InvoiceAmountDue")), 2);
    GridTotal = decimal.Round(GridTotal, 2) + decimal.Round(AmountTotal, 2);

    ///////////////////////////////////////

    var chk = (CheckBox)GridView1.FindControl("Checkbox1");
    if (chk != null)
    {
    if (chk.Checked == true)
    {

    GridView1.BackColor = System.Drawing.Color.Lime;

    }

    if (chk.Checked == false)
    {

    GridView1.BackColor = System.Drawing.Color.Transparent;

    }


    }



    ///////////////////////////////////////




    foreach (TableCell tCell in e.Row.Cells)
    {

    tCell.Style.Add("border-bottom", "1px Dashed #FF3300");

    tCell.Style.Add("border-left", "1px Dashed #FF3300");

    tCell.Style.Add("border-right", "1px Dashed #FF3300");
    }

    }
    if (e.Row.RowType == DataControlRowType.Footer)
    {
    Label lbl1 = (Label)e.Row.FindControl("OrderTotalFooter");
    lbl1.Text = GridTotal.ToString("c");

    Label lbl7 = (Label)e.Row.FindControl("OutputVATAmountFooterLabel");
    lbl7.Text = TotalVAT.ToString("c");

    Label lbl = (Label)e.Row.FindControl("TestFooter");
    lbl.Text = TotalSell.ToString("c");

    Label lbl2 = (Label)e.Row.FindControl("QuantityFooter");
    lbl2.Text = QuantityTotal.ToString();

    Label lbl3 = (Label)e.Row.FindControl("ProfitFooter");
    lbl3.Text = TotalProfit.ToString("c");

    Label lbl4 = (Label)e.Row.FindControl("PurchasePriceLabelFooter");
    lbl4.Text = TotalBuy.ToString("c");

    Label lbl6 = (Label)e.Row.FindControl("ProfitMarginLabelFooter");
    ProfitMargin = (TotalProfit / TotalBuy) * 100;
    lbl6.Text = ProfitMargin.ToString("F2");

    foreach (TableCell tCell in e.Row.Cells)
    {

    tCell.Style.Add("border-bottom", "1px Dashed #777");

    tCell.Style.Add("border-left", "1px Dashed #777");

    tCell.Style.Add("border-right", "1px Dashed #777");
    }


    }

    if (e.Row.RowType == DataControlRowType.Header)
    {
    foreach (TableCell tCell in e.Row.Cells)
    {

    tCell.Style.Add("border-bottom", "1px Dashed #888");

    tCell.Style.Add("border-left", "1px Dashed #888");

    tCell.Style.Add("border-right", "1px Dashed #888");
    }
    }




    }





    protected void Update_OnClientClick(object sender, EventArgs e)
    {
    }

    protected void CheckBox1_OnCheckedChanged(object sender, EventArgs e)
    {

    }
    }
    }



    [/PHP]


  • Moderators, Science, Health & Environment Moderators Posts: 8,920 Mod ✭✭✭✭mewso


    You need to databind the grid on the checkchanged.


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    mewso wrote: »
    You need to databind the grid on the checkchanged.

    I just tried that, what is happening now is that the GridView is databinding but is unticking the box I just ticked, on rebind! And I'm still not getting the green background I coded for when the box is ticked...

    [PHP]
    protected void CheckBox1_OnCheckedChanged(object sender, EventArgs e)
    {
    GridView1.DataBind();
    }[/PHP]


  • Moderators, Science, Health & Environment Moderators Posts: 8,920 Mod ✭✭✭✭mewso


    O.k. sorry I've thought about this a bit more and rebinding just resets the checkboxes which is annoying so I think you'll have to back to your checkchanged event which was working I think you said except for the footer stuff. You'll just need to access the footer row instead of using the current row. e.g. this:-
    Label lbtot = (Label)GridView1.FindControl("LabelTotal");
    

    should be
    Label lbtot = (Label)GridView1.FooterRow.FindControl("LabelTotal");
    

    I think that should work but hey it's wonky stuff this gridview coding. I should have looked at your code more closely before going off on a tangent.


  • Moderators, Science, Health & Environment Moderators Posts: 8,920 Mod ✭✭✭✭mewso


    Actually be careful with your original code as you are creating a variable called GridView1 for the current row. You should use something more descriptive that won't clash with the Grid's Id:-
    protected void CheckBox1_OnCheckedChanged(object sender, EventArgs e)
            {
    
                CheckBox currentChk= (CheckBox)sender;
    
                GridViewRow currentRow = (GridViewRow)currentChk.NamingContainer;
    
    
    
                if (currentChk.Checked)
                {
    
                    currentRow .BackColor = System.Drawing.Color.Lime;
    
                    Label lb = (Label)currentRow .FindControl("VATLabel");
                    Label lbtot = (Label)GridView1.FooterRow.FindControl("LabelTotal");
    
    
                    lbtot.Text = lb.Text;
    
    
                }
    
                else
                {
                    currentRow.BackColor = System.Drawing.Color.Transparent;
                    Label lbtot = (Label)GridView1.FooterRow.FindControl("LabelTotal");
    
                    lbtot.Text = "";
    
                }
            
            }  
    

    I'm still not sure if this will work because I can't really tell how you are doing those footers tbh.


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    I had to comment out:
    [PHP]
    //GridViewRow GridView1 = (GridViewRow)Checkbox1.NamingContainer;
    [/PHP]
    To be able to get the RowFooter option to be legal in my Checkbox event handler...

    Label lbtot2 = (Label)GridView1.FooterRow.FindControl("LabelTotal");

    Am just gonna try it now and see what happens...


  • Moderators, Science, Health & Environment Moderators Posts: 8,920 Mod ✭✭✭✭mewso


    Yes see my post above your variable name is clashing with the id of your gridview. Call it something else.


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    mewso wrote: »
    Yes see my post above your variable name is clashing with the id of your gridview. Call it something else.

    Hi Mewso, huge thanks for that, I can now acess my Label in the GridView footer after renaming the variable!

    I'm at my wits end though trying to use a foreach loop to iterate through the gridview labels (that I select with my Checkbox set up), to sum them in my GridView footer label...

    [PHP] protected void Update_OnClientClick(object sender, EventArgs e)
    {
    }

    protected void CheckBox1_OnCheckedChanged(object sender, EventArgs e)
    {

    CheckBox Checkbox1 = (CheckBox)sender;

    GridViewRow GridView2 = (GridViewRow)Checkbox1.NamingContainer;
    var chk = (CheckBox)GridView1.FindControl("Checkbox1");
    if (((CheckBox)GridView2.FindControl("Checkbox1")).Checked == true)
    {

    GridView2.BackColor = System.Drawing.Color.Lime;
    Label lb = (Label)GridView2.FindControl("VATLabel");
    Label lbtot = (Label)GridView2.FindControl("LabelTotal");
    lbtot.Text = lb.Text;

    double sum = 0;
    foreach (GridViewRow gvr in GridView1.Rows)

    {
    if (chk != null)
    {
    double amount;
    amount = Convert.ToDouble(gvr.Cells[11].Text);
    sum += amount;
    Label lbtotal = (Label)GridView1.FooterRow.FindControl("OrderTotalFooter");
    lbtotal.Text = sum.ToString();


    }

    else
    {
    return;
    }

    }

    }


    if (((CheckBox)GridView2.FindControl("Checkbox1")).Checked == false)
    {

    GridView2.BackColor = System.Drawing.Color.Transparent;
    if (chk != null)
    {
    double sum = 0;
    foreach (GridViewRow gvr in GridView1.Rows)
    {

    double amount;
    amount = Convert.ToDouble(gvr.Cells[5].Text);
    sum += amount;

    }




    }
    }
    }[/PHP]

    This should work, shouldn't it?!?


  • Advertisement
  • Moderators, Science, Health & Environment Moderators Posts: 8,920 Mod ✭✭✭✭mewso


    Again I recommend you try naming your variables so they make sense and you don't find yourself down the road wondering what something is or does. Your code needs some cleaning up I think. You are accessing the sender object, then the same checkbox in your if statement when you only need the sender. If you need to go through each row and compile a total based on the checkbox being checked or not in each row then you need to loop through the rows as you are doing but within the loop re-reference the checkbox and labels each time so you have the controls for the current row within the loop. I would write a separate procedure for that along these lines:-
    function ProcessTotals()    {
        var total = 0;
        foreach (GridViewRow gvr in GridView1.Rows)
        {
            var chk = (CheckBox)gvr.FindControl("CheckBox1"); //reference to the checkbox in the specific row
            if (chk.Checked)    {
                var label = (Label)gvt.FindControl("MyLabel");
                total += int32.parse(label.text);
            }
        }
    
        var footerTotal = (Label)GridView1.FooterRow.FindControl("MyTotalLabel");
        footerTotal = total.ToString();
    }
    

    Thats just a basic example of looping through every row in a grid and accessing controls to determine values etc. Your checkchanged can do some row specific stuff (changing bg colours and so on) and then call this procedure. I'm guessing your intentions tbh because some of that code seems a tad confusing. e.g. as you loop through each row you are doing some logic based on chk which is the checkbox that was just clicked not the checkbox for the current row in the loop but before that chk is probably null anyway because you are using GridView1.FindControl("CheckBox1") - remember the reason for using variable names that make sense. GridView1 is the actual grid so this will return null. Finally don't use return in the else within the loop. If you want to continue to the next row then remove the else completely. If you really do want to exit the loop then fine leave the return in there.


  • Closed Accounts Posts: 3,912 ✭✭✭HellFireClub


    Hi Mewso, HUGE HUGE HUGE thanks for helping me out with this, I have it all working now, based on your approach above with writing the code into a separate function, and a bit of fiddling with the controls!

    Thanks again and also to Giblet for the advice on the thread...


  • Moderators, Science, Health & Environment Moderators Posts: 8,920 Mod ✭✭✭✭mewso


    Good stuff. Now make the switch to MVC :)


Advertisement