Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Any button Onclick event is not working on my project. I inserted one more button called button1 for testing if it works but found that it is not working by changing the text of a label. Unfortunately, It is not working at all. Only page load event-driven is working.

The problem is not solved with other controls. For example, after the user clicks on an update button, a function will be called that checks the value in the textbox and make some calculation. After debugging, I found that the program cannot read any values from the textbox.

Note: I am using packages like bootstrap, Ajax as they are already built-in in the asp.net web forms web applications. I have also tried to exclude them from the project as mentioned in some references, however, nothing changed.


Update:
This is the source code of the mentioned page (the web Form page is for Displaying and Updating shopping cart.One more control is there which is a checkout Button, to proceed with the next steps.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ShoppingCart.aspx.cs" Inherits="Celebreno.ShoppingCart" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">



    <div id="ShoppingCartTitle" runat="server" class="ContentHead">
        <h1>Shopping Cart</h1>
    </div>

    <%--Start of the GridView to display the items in the cart--%>
    <asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
        ItemType="Celebreno.Models.ItemsInCart" SelectMethod="GetShoppingCartItems"
        CssClass="table table-striped table-bordered">
        <Columns>

            <%--problem solved : change "ID" to "ServicePack.ID"--%>
            <asp:BoundField DataField="ServicePack.ID" HeaderText="Service Package ID" SortExpression="ID" />
            <asp:BoundField DataField="ServicePack.Provider" HeaderText="Provider" />
            <asp:BoundField DataField="ServicePack.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}" />
            <asp:TemplateField HeaderText="Quantity">
                <ItemTemplate>
                    <asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.Quantity %>" ></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Item Total">
                <ItemTemplate>
                    <%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) *  Convert.ToDouble(Item.ServicePack.UnitPrice)))%>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Remove Item">
                <ItemTemplate>

                    <%--checkbox for removing the item--%>
                    <asp:CheckBox ID="Remove" runat="server"></asp:CheckBox>

                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <%--End of the GridView--%>

    <div>
        <p></p>
        
            <asp:Label ID="LblTotalText" runat="server" Text="Order Total: "></asp:Label>
            <asp:Label ID="LblTotal" runat="server" EnableViewState="false"></asp:Label>
        
    </div>
    <br />



    <table>
        <tr>
            <td>
                <asp:Button ID="UpdateBtn" runat="server" Text="Update" OnClick="UpdateBtn_Click" CausesValidation="False" UseSubmitBehavior="false" />
               
            </td>
            <td>

                <%--Checkout PlaceHolder--
                <asp:ImageButton ID="CheckoutImageBtn" runat="server"
                    ImageUrl="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif"
                    Width="145" AlternateText="Check out with PayPal"
                    OnClick="CheckoutBtn_Click"
                    BackColor="Transparent" BorderWidth="0" CausesValidation="False" /> --%>



                <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="CheckOut" CausesValidation="False" UseSubmitBehavior="false" />



            </td>
        </tr>
    </table>



</asp:Content>




And this is the Code Behind of the web page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


using Celebreno.Models;
using Celebreno.Cart;

//for cart update
using System.Collections.Specialized;
using System.Collections;
using System.Web.ModelBinding;



namespace Celebreno
{
    public partial class ShoppingCart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            //2- Display the total of cart by calling GetTotal() function(located in Actions_of_Cart class)
            //and then store the return value in a new variable, then dispaly it in a label
            using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
            {

                //declare a new variable to store the total into it
                decimal cartTotal = 0;
                cartTotal = usersShoppingCart.GetTotal();

                if (cartTotal > 0)
                {
                    //Display Total in a label that has property " Enable ViewState = False"
                    //      ViewSate used
                    LblTotal.Text = String.Format("{0:c}", cartTotal);
                }
                else
                {
                    LblTotalText.Text = "";
                    LblTotal.Text = "";
                    //HtmlGenericControl
                    ShoppingCartTitle.InnerText = "The Shopping Cart is Empty";
                    //not yet needed
                   UpdateBtn.Visible = false;
                    //CheckoutImageBtn.Visible = false;
                }
            }



        }










        //1- decalre the select Method (used in GridView in Source Code) to return the value of..
        //..calling GetCartItems(), which is defined in Actions_of_Cart DB class
        public List<ItemsInCart> GetShoppingCartItems()
        {
            Actions_of_Cart actions = new Actions_of_Cart();
            return actions.GetCartItems();
        }













        //for cart update
        //this will loop throw the items in the cart and call update and remove button
        public List<ItemsInCart> UpdateCartItems()
        {
            using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
            {
                String cartId = usersShoppingCart.GetCartId();

                Actions_of_Cart.ShoppingCartUpdates[] cartUpdates = new Actions_of_Cart.ShoppingCartUpdates[CartList.Rows.Count];
                for (int i = 0; i < CartList.Rows.Count; i++)
                {
                    IOrderedDictionary rowValues = new OrderedDictionary();
                    rowValues = GetValues(CartList.Rows[i]);
                    cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ProductID"]);

                    CheckBox cbRemove = new CheckBox();
                    cbRemove = (CheckBox)CartList.Rows[i].FindControl("Remove");
                    cartUpdates[i].RemoveItem = cbRemove.Checked;

                    TextBox quantityTextBox = new TextBox();
                    quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
                    cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString());


                    //TextBox quantityTextBox = new TextBox();
                    //quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
                    //int a = 0;
                    //if (Int32.TryParse(quantityTextBox.Text, out a ))
                    //{
                      //cartUpdates[i].PurchaseQuantity = a;
                    //}

                }


                usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
                CartList.DataBind();
                LblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
                return usersShoppingCart.GetCartItems();
            }
        }



        public static IOrderedDictionary GetValues(GridViewRow row)
        {
            IOrderedDictionary values = new OrderedDictionary();
            foreach (DataControlFieldCell cell in row.Cells)
            {
                if (cell.Visible)
                {
                    // Extract values from the cell.
                    cell.ContainingField.ExtractValuesFromCell(values, cell, row.RowState, true);
                }
            }
            return values;
        }




        protected void UpdateBtn_Click(object sender, EventArgs e)
        {
            UpdateCartItems();
        }









        protected void CheckoutBtn(object sender, ImageClickEventArgs e)
        {
            using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
            {
                Session["payment_amt"] = usersShoppingCart.GetTotal();
            }
            Response.Redirect("Checkout/CheckoutStart.aspx");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
            {
                Session["payment_amt"] = usersShoppingCart.GetTotal();
            }
            Response.Redirect("Checkout/CheckoutStart.aspx");
        }
    }
}


What I have tried:

I have solved the problem of button event handling by adding these attributes. but when comes to other types of controls, these attributes cannot be included, so that problem is not solved.

<pre><asp:Button ID="UpdateBtn" runat="server" OnClick="UpdateBtn_Click" Text="Button" CausesValidation="False" UseSubmitBehavior="false" />
Posted
Updated 25-Nov-19 3:48am
v3
Comments
F-ES Sitecore 25-Nov-19 4:15am    
Event handling and accessing controls all work. If they don't work for you it is something to do with your mark-up and code, but as you have posted neither it's hard to give specific advice.
Member 14192762 25-Nov-19 9:52am    
Hi, Thank you for your comment. I have updated the question and include the full code of the web page. By the way, the problem is happening in all the forms in the App, not only this one. Some of the controls, which I faced the problem with it is the Image Button, as you can see that I have tried to use a button instead of it to handle the click event, however this should not be the solution.
F-ES Sitecore 25-Nov-19 9:59am    
The click event for the ImageButton is "CheckoutBtn_Click" but the handler in the code is called "CheckoutBtn". The two have to match or else it won't be called.
DerekT-P 25-Nov-19 5:21am    
I suspect you're missing Autopostback="true" for the controls you want to postback. With that set on the relevant controls, you won't need your OnClick="[whatever]"
With autopostback, you're no longer explicitly stating what server-side method you want to invoke, so you need to declare that some other way. The simplest is to include AutoEventWireup=true in your page declaration (in the .aspx file). Then ASP.Net will associate methods with the default names ([control]_[event]) to your controls' postbacks. Alternatively, you can add the mapping explicitly server-side by adding "handles [control].[event]" to your method definitions; e.g.

Sub mypanel_hasbeenclicked(sender as Object, e as EventArgs) handles Panel1.Click

Just make sure you don't use both methods at once, or you may end up calling your methods twice (if they have the default names)
I'd also suggest that you investigate what's actually happening when you click a button; in Chrome, use Developer tools' "Network" panel to monitor the requests to the server - this will show you the actual data being sent to the server. In your C# code, set breakpoints in your page_load and other event handlers, so you get to understand the sequence of events at the server.
Member 14192762 29-Nov-19 15:12pm    
Thank you for your comment. Finally, I figured out the reason. It was because I had two form tags in my master page by mistake.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900