Member Avatar for adrian.mcguinness

I have a gridview which totals up the quantity of items the buyer has added to basket.
I have added a delete button and this button is meant to reduce the quantity by one when clicked. removing the latest record from the database. I keep getting a the following:

Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

My code is as follows:

 <asp:GridView ID="gvBasket" runat="server" AutoGenerateColumns="False">
     <Columns>
            <asp:BoundField DataField="ProductName" HeaderText="Product Name" SortExpression="ProductName" />
            <asp:BoundField DataField="qty" HeaderText="Quantity" SortExpression="qty" />
            <asp:BoundField DataField="UnitPrice" HeaderText="Unit Prce" SortExpression="unitPrice"
                HtmlEncode="false" DataFormatString="{0:c}" />
            <asp:TemplateField HeaderText="Total" SortExpression="Total">
                <ItemTemplate>
                    <asp:Label ID="lblTotal" runat="server" Text='<%# Eval("Total", "{0:c}") %>'  />
                </ItemTemplate>
                <FooterTemplate>
                <asp:Label ID="lblsubTotal" runat="server" />

                </FooterTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="sessionID" HeaderText="Session" 
                SortExpression="sessionID" visible="false"/>
            <asp:BoundField DataField="UserID" HeaderText="user" SortExpression="UserID" Visible="false" />
            <asp:BoundField DataField="ProductID" HeaderText="ProductID" 
                SortExpression="ProductID" visible="false"/>
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    <asp:Button ID="Delete" runat="server" 
                        CommandArgument='<%# Bind("productID") %>' onclick="Delete_Click" 
                        Text="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#003399" />
    </asp:GridView>

and code behind is:

      protected void Delete_Click(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Button btn = (Button)sender;
                int id = int.Parse(btn.CommandArgument);

                string Query = "DELETE FROM ShoppingBasket WHERE Date IN (SELECT TOP 1 Date FROM shoppingBasket WHERE  ProductID = " + id + " AND UserID = '" + (string)Session["UserName"] + "' ORDER BY Date DESC)";

                ConnectionHandler objHandler = new ConnectionHandler();
                DataTable dt = objHandler.ExecuteSelect(Query);
            }

I have tried adding to pages: EnableEventValidation="true" without success.

You can't handle the button's click event inside the GridView instead you've to handle the RowCommad event of GridView by setting CommandName property.

Demo:

.aspx markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("ID") %>' 
                    CommandName="cmdDelete" Text="Delete" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
and code-behind (.cs)
public class Foo
{
    public int ID { get; set; }
    public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        List<Foo> fooList = new List<Foo>()
        {
                new Foo(){ ID=1, Name="Name1"},
                new Foo(){ ID=2, Name="Name2"},
        };
        GridView1.DataSource = fooList;
        GridView1.DataBind();
    }
    GridView1.RowCommand += (sa, ea) =>
    {
        if (ea.CommandName == "cmdDelete")
        {
            string id = ea.CommandArgument.ToString();
            Response.Write("Code to delete record whose id is " + id);
        }
    };
}
Member Avatar for adrian.mcguinness

Ive added a CommandName property to the button but am unsure how to set this to RowCommand Do i need to change my code behind.

Member Avatar for adrian.mcguinness

hi does it help if i give you my DAL code.

  public class ConnectionHandler
    {
        SqlConnection cn;
        void connect()
        {
            string cnstr = System.Configuration.ConfigurationManager.ConnectionStrings["ShoppingCart"].ConnectionString;
            cn = new SqlConnection(cnstr);
            cn.Open();
        }
        public DataTable ExecuteSelect(string Query)
        {
            connect();


            SqlDataAdapter da = new SqlDataAdapter(Query, cn);

            DataSet ds = new DataSet();

            da.Fill(ds);

            DataTable dt = ds.Tables[0];

            return dt;
        }

        public int ExecuteStatement(string Query)
        {
            connect();
            SqlCommand cmd = new SqlCommand(Query, cn);

            return cmd.ExecuteNonQuery();
        }


    }

Im quite new to this and still cant quite get the hang of it. This is my Connection to the database.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.