<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" onrowediting="GridView1_RowEditing">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" />
<asp:Label ID="lblFirstColumn" runat="server" Text='<%# Eval("FirstColumn") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditMode" runat="server" Text="This is Edit mode"></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("FirstColumn", typeof(int));
dt.Rows.Add(100);
GridView1.DataSource = dt;
if (!IsPostBack)
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
If I change if (!IsPostBack) GridView1.DataBind(); to GridView1.DataBind(); and try to put GridView into Edit mode by clicking btnEdit, then I get the exception:
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.
But if I set EnableEventValidation to false, then GridView1 won’t enter edit mode ( ie - GridView1_RowEditing doesn’t get called ).
BTW – same problem also occurs with other databound controls ( DataList, DetailsView )
Page. EnableEventValidation gets or
sets a value indicating whether the
page validates postback and callback
events. When the EnableEventValidation
property is set to true, ASP.NET
validates that a control event
originated from the user interface
that was rendered by that control. A
control registers its events during
rendering and then validates the
events during postback or callback
handling.
a) Why must postback and callback events be evaluated? and how exactly does evaluation happen?
b) Why would calling GridView1.Databind() on each postback cause exception when trying to put it into edit mode?
c) I also don’t see any reasons why disabling EnableEventValidation prevents GridView from entering edit mode?! Thus why did
thank you
There is a good article about how and why you would want to use EventValidation here:
http://odetocode.com/blogs/scott/archive/2006/03/21/asp-net-event-validation-and-invalid-callback-or-postback-argument-again.aspx
and MSDN:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableeventvalidation.aspx
The short answer is event validation is designed to protect the web site from having values injected into the page that can be used to exploit your application in some way.
Related
Inside a RadGrid, I have a drop RadComboBox that is populated by a web service.
I am using an EditItemTemplate nested inside a GridTemplateColumn to hold it, as shown:
On the server side, how can I access the value chosen by the user from the RadComboBox?
<telerik:GridTemplateColumn UniqueName="UserCol" HeaderText="proto user" DataField="UserID">
<EditItemTemplate>
<telerik:RadComboBox ID="RadComboBox1" runat="server" AutoPostBack="false" CausesValidation="true"
Width="240" MaxHeight="200px" OnItemsRequested="ddEmployee_ItemsRequested" AllowCustomText="true"
EnableLoadOnDemand="true" ShowMoreResultsBox="true" EnableVirtualScrolling="true"
MarkFirstMatch="false" >
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
It depends on what event you're handling.
You can set AutoPostBack="true" and handle the OnSelectedIndexChanged event of the RadComboBox. This is very straightforward as you can get the selected value either from the EventArgs or from the sender object which is the RadComboBox itself.
Check this out: http://www.telerik.com/help/aspnet-ajax/combobox-server-side-selectedindexchanged.html
If you are handling a row operation event such as insert or update, you need to find the RadComboBox object from the GridItem (e.Item).
protected void RadGrid_RowOperation(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
// this will find the control
RadComboBox RadComboBox1 = (RadComboBox)(e.Item.FindControl("RadComboBox1"));
// so you can get the selected value
string value = RadComboBox1.SelectedValue;
}
Here is my DataGridView
<asp:GridView ID="gvPredstave" runat="server" CssClass="gridview"
AlternatingRowStyle-CssClass="even" AutoGenerateColumns="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnRezervisi" runat="server" Text="Rezervisi" onclick="Button1_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my code for click on button in GridView
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("AktivneRezervacije.aspx?korisnicko_ime=" + korisnicko_ime);
conn.Close();
}
When i click on button i got this error in browser:
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.
Does anybody know the reason why is this happening.
I tried with EnableEventValidation="false" but it doesn't work.
I recreated the error using your gridView and binding it. The answer lies on the Page_Load event. If you have it like this:
protected void Page_Load(object sender, EventArgs e)
{
bindGridView(); //code to bind the GridView
}
You will get the exception. Change it to:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridView();
}
}
and you should not get the error anymore.
if the page is in postback,
you have two ways to make it work
either add a postback event on your gridview
or control in on page load.
Regarding to the conn.close();
close first the connection after redirecting it to another page.
happy coding.
Very famous error message (see below), judging by the number of Google results. But every one of them I've seen suggests to set EnableEventValidation to false. I have searched my entire codebase, and I cannot find the string "EnableEventValidation" anywhere. Moreover, this code used to work; something I have done has obviously broken the pages. But what?
The error happens when I click on a button inside a Telerik RadGrid, declared as:
<telerik:RadGrid ID="MyGrid" Width="100%" ItemStyle-BorderColor="Gainsboro"
ItemStyle-BorderStyle="Solid" ItemStyle-BorderWidth="1px" ActiveItemStyle-BackColor="Bisque"
SelectedItemStyle-BackColor="Black" AllowPaging="True" PageSize="15" runat="server"
AllowSorting="true" OnItemCommand="MyGrid_ItemCommand" AutoGenerateColumns="false"
OnNeedDataSource="MyGrid_NeedDataSource" GridLines="Horizontal" AllowMultiRowSelection="false"
Skin="Black">
<GroupingSettings CaseSensitive="false" />
<MasterTableView Width="100%" DataKeyNames="ID" AllowFilteringByColumn="false" Font-Names="Arial"
Font-Size="10px">
<Columns>
<telerik:GridButtonColumn ButtonType="PushButton" Text="Cancel" CommandName="Cancel"
ConfirmText="Are you sure you want to cancel this?">
</telerik:GridButtonColumn>
...
</Columns>
</MasterTableView>
<PagerStyle Mode="NextPrevAndNumeric" />
<FilterMenu EnableTheming="True">
<CollapseAnimation Duration="200" Type="OutQuint" />
</FilterMenu>
</telerik:RadGrid>
click on the "Cancel" button, and here's the famous error:
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.
Here's the problem: in my Page_Load method I had:
protected void Page_Load(object sender, EventArgs e) {
MyGrid.Rebind();
}
The rebinding of the grid on postback was obviously screwing something up. I changed it to:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
MyGrid.Rebind();
}
}
and everything is working now.
I had the same problem but I had no Grid.Rebind() or Grid.Databind() in my NeedDataSource method or Page_Load method. This happened just after I drag a column to be grouped and then order the grouped column ASC/DESC
I simply added
EnableEventValidation="false"
in the <%# Page %> tag of my .aspx page. The ordering fails but at least I no longer get the error. As a note everything else works perfectly except the ordering of a grouped column
here is the code I use in the NeedDataSource method
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
String connstr = ConfigurationManager.ConnectionStrings["PrimeIntegartionsConnectionString"].ConnectionString;
SqlDataSource Ds = new SqlDataSource(connstr, BuildSql()); //buildsql simply returns a SQLSelect String "select * from example"
RadGrid1.DataSource = Ds;
}
ASCX File:
<asp:datagrid runat="server" id="gridFormFields" datakeyfield="FieldID"
autogeneratecolumns="False"
onitemcommand="gridFormFields_ItemCommand" onitemdatabound="gridFormFields_ItemDataBound">
<columns>
<asp:templatecolumn>
<itemtemplate>
<asp:imagebutton runat="server" id="buttonMoveUpFormField" resourcekey="buttonMoveUpFormField"
commandname="Item" commandargument="MoveUp" imageurl="~/images/up.gif" />
</itemtemplate>
</asp:templatecolumn>
<asp:templatecolumn>
<itemtemplate>
<asp:imagebutton runat="server" id="buttonMoveDownFormField" resourcekey="buttonMoveDownFormField"
commandname="Item" commandargument="MoveDown" imageurl="~/images/dn.gif" />
</itemtemplate>
</asp:templatecolumn>
</columns>
Code behind:
protected void gridFormFields_ItemDataBound(object sender, DataGridItemEventArgs e)
{
(e.Item.FindControl("buttonMoveUpFormField") as ImageButton)
.Visible = gridFormFields.Items.Count > 1 && e.Item.ItemIndex > 0;
(e.Item.FindControl("buttonMoveDownFormField") as ImageButton)
.Visible = gridFormFields.Items.Count > 1 && e.Item.ItemIndex < gridFormFields.Items.Count - 1;
}
In the code behind, the Control returned by FindControl is null. Why?
How can I access the buttonMoveUpFormField and buttonMoveDownFormField controls?
From the code behind, is it possible to access controls which are declared in the ItemTemplate section of the TemplateColumn section of a DataGrid?
Because you need to add code to include "Item" and "AlternatingItem" and exclude all other types, before you try to find that control.
if (e.Item.Type == ...
You can certainly access the controls that are within the ItemTemplate section. I'm dealing with a similar issue. One thing that I've found is, depending what is calling your "gridFormFields_ItemDataBound", you may not have access to those controls yet.
I know that in my instance, I've got an "ItemTemplate" and an "EditItemTemplate", when I click edit, it fires an event "RowEditing" before it is actually switched to "Edit Mode", so the control will not be there yet. I do though have access to the controls in "RowUpdating" which is fired when I click save in the edit mode.
Maybe this helps? For example, your "OnDataBound" might be the event that is trying to access your controls, but you may not have access to them on databound?
Just a thought. I'll edit this if I get any further on mine.
I have a fairly simple form:
<asp:FormView>
<EditItemTemplate>
<asp:LoginView>
<RoleGroups>
<asp:RoleGroup roles="Blah">
<ContentTemplate>
<!-- Databound Controls using Bind/Eval -->
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
<!-- Databound Controls -->
</EditItemTemplate>
</asp:FormView>
<asp:LinqDataSource OnUpdating="MyDataSource_Updating" />
I handle my LinqDataSource OnUpdating event and do some work handling some M:N fields. That all works.
However, once the update is finished (and I call e.Cancel = true), the LoginView control does not databind its children... so they are all blank. The FormView's viewstate is still fine, as all the rest of the controls outside of the LoginView appear fine. I even handle the FormView_DataBound event and a Trace shows that the FormView is being databound on postback.
Why then is the LoginView not keeping its ViewState/being databound? Here's a sample code snippet showing the flow:
protected void MyDataSource_Updating(object s, LinqDataSourceUpdateEventArgs e)
{
try
{
Controller.DoSomething(newData);
// attempts to databind again here fail
// frmView.DataBind();
// MyDataSource.DataBind();
// LoginView.DataBind();
}
catch { // blah }
finally
{
e.Cancel = true;
}
}
I fixed this by reverting to the age old method of databinding everything myself and axing the LoginView.
Ok, i don't know if you need help at this time, but the contaiter that you need to catch is de FormItem, in this case you cant do this
<%# DataBinder.Eval(((FormItem)Container.Parent).DataItem,"YOUR FIELD") %>
Sorry for my english.
Bye.