OnClick Event for Button in GridView is not working - asp.net

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.

Related

UpdatePanel with TextBox.OnTextChanged Async Event not firing

I have a textbox for inputting a desired username. When the user types in their name and the input loses focus, I want to send an async postback to check whether their username is already taken. This works fine in the cases that no error is thrown, but I want to handle errors, as well.
Per MSDN, I've added an AsyncPostBackError handler to the ScriptManager. I've tried this both on every page load and only on non-postback page loads.
I have my TextBox in an UpdatePanel like so:
<asp:UpdatePanel ID="upLogin" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="tbLogin" runat="server" placeholder="username"
OnTextChanged="tbLogin_TextChanged" required />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tbLogin" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
In the code-behind, I have:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).AsyncPostBackError +=
BootstrapLogin_AsyncPostBackError;
}
void BootstrapLogin_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
tbLogin.Attributes.Remove("data-success");
tbLogin.Attributes["data-error-message"] = myErrorMessage;
}
protected void tbLogin_TextChanged(object sender, EventArgs e)
{
throw new Exception("what?");
}
I also added Async="true" to my Default.aspx Page markup.
When I have AutoPostBack="true" on my TextBox, the error is thrown and the AsyncPostBackError handler is never called. For some reason, during the postback, Page.IsAsync is false. I suspect this is the reason (or indication of why) it's not being handled.
When I set AutoPostBack="false", no postback is fired at all, despite the specified trigger.
Ideas?
It looks like following code doesn't work as intended
ScriptManager.GetCurrent(Page).AsyncPostBackError +=
BootstrapLogin_AsyncPostBackError;
Instead of that I just set the OnAsyncPostBackError property of the ScriptManager in markup and it worked with AutoPostback = "True" in your TextBox.
<asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="BootstrapLogin_AsyncPostBackError"></asp:ScriptManager>
Not sure why your code didn't work. It picks up the correct ScriptManager.
UPDATE
Solved it!
I should refresh my knowledge on Page lifecycle :(
Actually, we should add your code into Page_Init rather than in Page_Load. Following works perfectly.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ScriptManager.GetCurrent(Page).AsyncPostBackError +=
BootstrapLogin_AsyncPostBackError;
}
UPDATE 2
See this screen capture
Hope this helped!

Button Control not working with RowCommand Event

<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="lbShowGroup" CommandName="View" CommandArgument='<%# Eval("Topic") %>'
runat="server" Text="View"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
Code behind:
protected void tblTopics_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
Response.Redirect("Group.aspx?Topic=" + e.CommandArgument.ToString());
}
}
Debugging doesn't reach the RowCommand event, but when I change the button control to LinkButton, it works. What's wrong?
Do you databind your grid on postbacks?
You must not bind your grid on postbacks in Page_Load, only when something has changed that causes the GridView to reload data(f.e. Sorting,Paging) and only in the appropriate even-handlers.
So wrap the databinding in a PostBack-check:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
DataBindGrid();
}
}
Another possible reason: Have you disabled ViewState somewhere?
I had the same issue and found out that my problem was in the Master Page where EnableViewState="false".
I changed the Master page to use EnableViewState="True".
And the rowcommand event fired as expected.

How to get Postback Data on LinkButton Click Event?

I have a LinkButton in aspx page.
<asp:TextBox ID="textBoxNote" runat="server" />
<asp:LinkButton ID="linkButtonUpdateNote" Text="Update" OnClick="ButtonUpdateNoteClicked" runat="server" />
the click event handler has the following code
protected void ButtonUpdateNoteClicked(object sender, EventArgs e)
{
var note = textBoxNote.Text;
}
On Postback textBoxNote.Text is empty. I don't get the posted value. How to get the value?
It seems like you are possibly resetting the value in your Page_Load.
Check that you are using IsPostback check in the Page_Load function. see - http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
private void Page_Load()
{
if (!IsPostBack)
{
DoThisOnce();
}
DoThisOnEachPostback();
}

Invalid postback or callback argument - button in Telerik grid

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;
}

Why won't my LinkButton inside a GridView raise its OnClick event?

I have a LinkButton inside a GridView (via an TemplateField). No matter what I try, the LinkButton will not invoke its event handler. I have tried both:
A traditional event handler ("OnClick")
A OnRowCommand event handler at the GridView level.
In both cases, I've debugged and it doesn't even catch the event handler.
If I move the LinkButton out on the page (so it's not in the GridView), it works fine, so I know the syntax is right.
Here is the "traditional" method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" OnClick="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
What's interesting is if I remove the "CancelThis" method from the code behind, it throws an error. So I know it's aware of its event handler, because it looks for it when it compiles.
Here is the RowCommand method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" CommandName="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
In this case, the GridView has:
OnRowCommand="GridView_RowCommand"
It postsback, but never hints at raising the event.
Any idea what I'm missing here?
How are you binding your GridView? Are you using a datasource control? If you are binding manually during Page_Load, it's possible that since the grid is binding every round trip, the event handler isn't catching properly. If this is the case, you may want to try something like:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//do binding
}
}
Can you post sample binding code to go with your markup?
If you really want to force the issue, you could hook into the RowDataBound event on the Grid, find the button manually and add the handler in the code behind. Something like:
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowDataBound="gvTest_RowDataBound" />
code behind:
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//find button in this row
LinkButton button = e.Row.FindControl("DeleteButton") as button;
if(button != null)
{
button.Click += new EventHandler("DeleteButton_Click");
}
}
}
protected void DeleteButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
// do as needed based on button.
}
I'm not sure what the purpose of the button is, but assuming it is a row delete button, you may not want to take this approach as in the event handler, you don't have direct access to the row in question, like you would using the RowCommand event.
Is there a reason you're using the Template field? Vs say a ButtonField? If you use a ButtonField, then you can hook into the RowCommand event.
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowCommand="gvTest_RowCommand">
<columns>
<asp:buttonfield buttontype="Link" commandname="Delete" text="Delete"/>
....
</columns>
</asp:GridView>
code behind:
protected void gvTest_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Delete")
{
//take action as needed on this row, for example
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow currentRow = (sender as GridView).Rows[rowIndex];
//do something against the row...
}
}
You might want to consult MSDN docs on some of these topics:
RowCommandEvent
ButtonField class
EDIT:
To answer your question on the ButtonField - yes I don't see why you couldn't still deal with a buttonfield. Here's a snippet to find the buttonfield during row data bound and hide it (untested but I think would work...)
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//let's assume your buttonfield is in column 1
// (you'd know this based on your markup...)
DataControlFieldCell cell = e.Row.Cells[1] as DataControlFieldCell;
if(cell != null)
{
ButtonField field = cell.ContainingField as ButtonField;
//based on your criteria, show or hide the button
field.Visible = false;
//or
field.Visible = true;
}
}
}
Is viewstate turned on on your GridView? This has caught me out numerous times.
<button onclick="window.open('<%#Eval("ReportLinks")%>', '_blank');" title='<%#Eval("ReportLinks")%>'> Link</button>

Resources