2
votes

I am working in ASP .net 2.0. I am a learner. I have a grid view which has a button in it. Please find the asp mark up below

<form id="form1" runat="server">
<div>
    <asp:GridView ID="myGridView" runat="server">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Button CommandName="AddARowBelow" Text="Add A Row Below"   runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>
</form>

Please find the code behind below.

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

namespace GridViewDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable("myTable");
            dt.Columns.Add("col1");
            dt.Columns.Add("col2");
            dt.Columns.Add("col3");
            dt.Rows.Add(1, 2, 3);
            dt.Rows.Add(1, 2, 3);
            dt.Rows.Add(1, 2, 3);
            dt.Rows.Add(1, 2, 3);
            dt.Rows.Add(1, 2, 3);
            myGridView.DataSource = dt;
            myGridView.DataBind();
        }

        protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {

        }
    }
}

I was thinking that when I click the command button, it would fire the mygridview_rowcommand() but instead it threw an error as follows:

Invalid postback or callback argument. Event validation is enabled using 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.

Can any one let me know on where I am going wrong?

1

1 Answers

1
votes

First, try to disable event validation and see what the result is, since that is the obvious problem in your code.

<%@ Page EnableEventValidation="false" ...

However, if you don't want to restort to such a hack, do the following:

After that, delete the OnCommand event from the button's attributes, and add an OnRowCommand event to the GridView itself.

Example:

<asp:GridView OnRowCommand="myGridView_RowCommand">
    ...
</asp:GridView>

This should be the correct way of handling these commands.
The button must have a specific CommandName in order for it to work as intended.

See this page for possible values and more explanation of this issue. There is also a working example on that page, it is worth your time to check it out.