C# - ASP.NET Button click event not working - c#

I have an ASP.NET (C#) page with some 3rd party controls, some ajaxy stuff and some normal ASP.NET Button controls.
The Button click events do not fire when clicked.
Double-clicking the button in design mode in VS 2008 switches to the code-behind but doesn't create the event handler.
Creating the event handler manually doesn't help.
The whole page is too big to include here, but this is the top bit:
<%# Page Language="C#" MasterPageFile="~/basewidepage2.master" AutoEventWireup="true" EnableEventValidation="false" CodeFile="CompanyCompliance.aspx.cs" Inherits="CompanyCompliancePage" Title="3DSS" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%# Register Assembly="obout_Grid_NET" Namespace="Obout.Grid" TagPrefix="cc2" %>
<%# Register Src="usercontrols/CalendarEx.ascx" TagName="CalendarEx" TagPrefix="uc2" %>
<%# MasterType VirtualPath="~/basewidepage2.master" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceholder1" runat="Server">
<script type="text/javascript">
// a bunch of function declarations
</script>
...and my button declaration on the page:
<asp:Button ID="LicenseCsvButton" runat="server" Text="Export to CSV" OnClick="LicenseCsvButton_Click" />
...and the code-behind:
protected void LicenseCsvButton_Click(object sender, EventArgs e)
{
// get data
CompanyCompliance cc = new CompanyCompliance(Master.theCompany.ID);
DataTable dt = cc.BusinessLicenses.Tables[0];
// send to browser as download
Tools.SendTableAsCsvToBrowser(Response, dt, "LicenseData");
}
Any ideas? could it be the ajax or something? Maybe the 3rd party "obout" grid control?
Update:
I did fix this a month or two ago, so I came back to this question to answer it for posterity but couldn't remember exactly how I fixed it! (Curse you, old age!) I had some limited success by replacing some of the ASP.NET AJAX controls with jQuery UI ones but I think the real solution was that one of the properties in the one of the tags was pointing to a control that no longer existed.
If you're in this same situation, try that and let me know what works in the comments and I'll post the correct answer.

During debugging, check the CausesValidation property of your button. For some reason, one of my pages had a button defaulting to "True." When I explicitly set it to "False" everything worked.

I know that this should be resolved by now, but just to share - I just had a similar issue. In my case, the problem was that I had a RequiredFieldValidator in a page, that wasn't visible because it was part of a popup. That validator was supposed to be invoked only when clicking its related "Save" button, but since I didn't have any ValidationGroup set, it would prevent the page to submit for any clicked button. Adding a ValidationGroup to the right button resolved the issue.

Experienced the same issue recently - cause was eventually determined to be that the button was disabled by a juavascript method onbeforesubmit (designed to prevent multiple submissions), and unfortunately web forms appears to check the enabled state of the button before it allows the codebehind event to trigger.

I had this problem just now and it was caused by another control having an AutoPostBack="true" which would submit the form before the button had a chance to submit the form to trigger the click event.

Change
CodeFile="CompanyCompliance.aspx.cs"
to
CodeBehind="CompanyCompliance.aspx.cs"
Related question: CodeFile vs CodeBehind

The inherits directive seems to point to a non-existant type.
Take a look in the code behind file of the CompanyCompliance page - ("CompanyCompliance.aspx.cs").
you should find the correct namespace and something like "public partial class xxx" where xxx is the name of the class which should correspond with your inherits directive. maybe you have to fully qualify the name as TJB already stated.

I had a similar issue, and it was really tricky. I recently migrated a VS 2005 ASP.NET 2.0 web forms app to VS 2010 ASP.NET 4.0.
It was difficult to setup and buggy as expected, but the issue of buttons not firing the click event was getting on my nerves.
In the end, it was as simple as not declaring a submit action in the site.master form. I changed:
<FORM runat="server" name="MainForm" method="post" action="Default.aspx" id="m_mainForm" enctype="multipart/form-data">
to
<FORM runat="server" name="MainForm" method="post" id="m_mainForm" enctype="multipart/form-data">
Boom. Problem solved. I hope it saves days of troubleshooting to someone. Sadly, I couldn't find anything about it on the internet by myself.

I had this problem I have changed the Button property "UseSubmitBehavior"=false. Now it is working.

For future answer seekers : If you are assigning the click handler in code behind, make sure that it is not inside an IsPostBack == false check :
void Page_Load (object oSender, EventArgs oEventArgs)
{
if (IsPostBack == false)
{
oButton += new EventHandler(oButton_Click); // does not work
}
oButton += new EventHandler(oButton_Click); // does work
}

Related

Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventvalidation =”true” %>

I am getting the below detailed error:
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventvalidation =”true” %> in a page. For security purpose, this feature verifies that arguments to postback or callback events originate from the server that originally rendered them.
I am having a webpart page with a webpart where i do have a UPdatePanel and a button Upon Button click i am getting this error.
the same package(wsp) which we are using in one of our environment is working fine and the same is not working in another environment.
Help in this is highly appreciable.
Without code it will be incredibly difficult to diagnose your issue.
You mentioned that your utilizing an Update Panel, which in essence will automatically store your page in memory, then it will render the proper Ajax to hide the Postback. The Microsoft Developer Network (MSDN) basically warns you when you use the EnableEventValidation with Client-Side modification.
If you write client script that changes a control in the client at run
time, you might have to use the RegisterForEventValidation method in
order to avoid false event validation errors.
Also if you initialize out of your web.config and directly in code, you should ensure that you call the validation before the page has been initialized. So I would potentially use:
protected void Page_PreInit()
{
// Before Page Initialization
}
Which would potentially eliminate any errors from the front-end, without code can't be of more assistance.
Ok without some code to go on I'll fire some rounds off into the dark, I know next to nothing about SharePoint so I maybe missing something obvious here:
Firstly, check your environments, one may have a different web.config which has EnableEventValidation set to false.
Secondly on Page_Load are you doing any DataBind? Depending on whatever your code is doing you may need make sure it's not binding on PostBack - or if it is already; try binding on PostBack.
Thirdly; any html or < > characters being included anywhere in the form? Also line breaks in data (my memory is a bit hazy on this one) I seem to remember, something like:
<option value="
my value
">select this</option>
Could cause it too. So doing a Trim() on data is recommended.
Lastly: Tag bleed out, check none of your tags are unclosed, something like <span <asp:TextBox [...] /> this could be the cause too.
add EnableEventValidation="false" in page directive <%# Page EnableEventValidation="false" %>

asp.net Button OnClick event not firing

I have problem in asp.net button control.
I define a button in form, onclick event of button is not firing when I click on the button.
<asp:Button ID="btn_QuaSave" runat="server" Text="SAVE" OnClick="btn_QuaSave_Click" />
protected void btn_QuaSave_Click(object sender, EventArgs e)
{
}
Because your button is in control it could be that there is a validation from another control that don't allow the button to submit.
The result in my case was to add CausesValidation property to the button:
<asp:Button ID="btn_QuaSave" runat="server" Text="SAVE" OnClick="btn_QuaSave_Click" CausesValidation="False"/>
Have you copied this method from other page/application ? if yes then it will not work, So you need to delete the event and event name assigned to the button then go to design and go to button even properties go to onClick event double click next to it, it will generate event and it automatically assigns event name to the button.
this should work
I had the same problem, my aspnet button's click was not firing. It turns out that some where on other part of the page has an input with html "required" attribute on.
This might be sound strange, but once I remove the required attribute, the button just works normally.
If you are using updatepanel on onclick event, this may happen.
Use 'EnableEventValidation="false"' in your page markup like this :
<%# Page Language="C#" MasterPageFile="~/ars_home.master" AutoEventWireup="true" CodeFile="Transaction_Window.aspx.cs" Inherits="Transaction_Window" EnableEventValidation="false" %>
Hope this helps
I had a similar issue and none of the answers worked for me. Maybe someone finds my solution helpful. In case you do not mind submitting on button click, only attaching to click event setting UseSubmitBehavior="false" may be worth trying.
In my case I put required="required" inside CKEditor control.
Removing this attribute fixed the issue.
Before
<CKEditor:CKEditorControl ID="txtDescription" BasePath="/ckeditor/" runat="server" required="required"></CKEditor:CKEditorControl>
After
<CKEditor:CKEditorControl ID="txtDescription" BasePath="/ckeditor/" runat="server"></CKEditor:CKEditorControl>
i had the same problem did all changed the button and all above mentioned methods then I did a simple thing I was using two forms on a single page and form with in the form so I removed one and it worked :)
Try to Clean your solution and then try once again.
It will definitely work. Because every thing in code seems to be ok.
Go through this link for cleaning solution>
http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/e53aab69-75b9-434a-bde3-74ca0865c165/
Try to go into Design mode in Visual Studio, locate the button and double click the button that should setup the event. Otherwise once the button is selected in Design more, go to the properties and try setting it from there.
Add validation groups for your validator elements. This allows you distinguish between different groups which to include in validation. Add validation group also to your submit button
in my case:
make sure not exist any form element in your page other than top main form,
this cause events not fired
If the asp button is inside tag then also the Click event will not raise.
Hope it's useful to some one.
In the case of nesting the LinkButton within a Repeater you must using something similar to the following:
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="MyUpdate">LinkButton</asp:LinkButton>
protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("MyUpdate"))
{
// some code
}
}
If it's throwing no error but still not firing the click event when you click the submit button, try to add action="YourPage.aspx" to your form.
Even i had two forms one for desktop view and other for mobile view , Removed one formed worked for me . I dint knew asp.page should have only one form.
Try this onserverclick
<button id ="DemoButton" runat="server" onserverclick="button_Click">Login</button>

PostBack Events Not Firing form Controls a bug from visual studio?

I think i'm missing something. What is the proper way to display an html div, for example, if the actual condition is met using Page_Onload + isPostBack + asp:button as a trigger for the event as following:
Page_Load -> Click event fired
Page load - element(a dynamically generted string for multiple table rows in this case)
status hidden
Client click submit button:
Element toggled to visible.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
nothing yet
}
else
{
suppose to check on client event handle by asp button
}
}
// So here is the event fired by client
protected void imgButSbmt_Click(object sender, ImageClickEventArgs e)
{
initializeReportTable();
}
and suddenly while trying to make sure I am correct with this argument,
I could see that imgButSbmt_Click is not "hitting" (with break Point attached while in debugging mode).
So first... I could note at this time that it's an unusual behavior (and while I am writing this question supposbly related to all my projects, this one was not firing at all events, so I solved it by deleting the solution file as I was writing this post).
So now, it does work.
BUT... this time (while solution is not yet to be Created) I re-opened my website "project" via File-Open-Website.
Hit F5 ...break Point works fine in red color.. no explanation marks this time. However, all events from the button & Drop down List that are configured to AutoPostBack
protected void DDL_Month(object sender, EventArgs e)
{
initializeReportTable();
}
were not firing. All events except for Page_Load are firing now. After checking again it does fire but only on the second time!
What is happening here?
I remembered some readings I came across awhile ago that said I should check the autoeventwireup and make sure it is set to true (it's the default I think).
So these are the page directives:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Here is an example of a control DropDownList + imgButton within a table:
<td>
<asp:DropDownList ID="DDL_Month" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDL_Month"></asp:DropDownList>
</td>
<td>
<asp:ImageButton ID="imgButSbmt" ImageUrl="images/sendreq.png"
runat="server" Height="25px" OnClick="imgButSbmt_Click"
style="margin-right: 0px; border-width:" />
</td>
as sugested by #JonH , and as a solution i've already had to use in some other even bugier scenario
if you're experiencing any UCB (un identified Code Behavior)...
just do as follow
1) open a new folder as a new home for the project Work-folder
2) copy all sub folders from The Buggy project, such as images, js etc'
3) Create a new webSite / any other application you had unusual problems with
then just apply all references needed for the application , copy codes to newly created .cs/vb/aspx
accordingly , use exisiting items (your other classes that are in separeted files)
and now you're ready to continue working...
the bugs should be behind you by now
just don't forget to delete the old project and any solutions files associated with it.
hope it will help some of other fresh developers who also encounterd the U.C.B Phenomenon

ascx runat server script

I have default.aspx with a "Submit" Button and a code behind function called as "btn_Submit" which will perform submit action. Once I deploy the application and if there is any logical problem in btn_Submit code, then I can use runat=server script in default.aspx file and I need not go for another deployment.
But When I tried the same for ascx file, it works very well in development environment i.e in VS but when I move the same to Test server, system throws function not defined. I have renamed the existing function name.
So is it possible to add runat=server script and add c# code in ascx file?
Yes it is possible..
You have to surround your code with markup
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
//hello, world!
}
</script>
Take a look to thisquestion! I think it will help you..
But it is really better to separate your code..
Did you tell the button which method to run on submit? With "auto event wireup" it will try to find a "buttonname_Click" method if you didn't specify anything. If that doesn't exist, you will get an error.
To call a method with a different name, specify that in the OnClick property of the button.
I am not sure why this happened and still was not able to solve it, So redeployed the application :(

OnClick event for ImageMap never never being invoked

I have an ImageMap control in an ascx file of mine. I'm trying to make something happen when the user clicks on an area in the map, but the page just posts back without my "imageMap_Click" event handler never being invoked. Suggestions?
<asp:ImageMap ID="imageMap" runat="server" ImageUrl="~/images/MapImages/map.jpg" HotSpotMode="PostBack" OnClick="imageMap_Click">
My imageMap_Click looks like this, just to see if it's invoked at all:
protected void imageMap_Click(object sender, ImageMapEventArgs e)
{
throw new NotImplementedException();
}
I've found it already. It was due to the control having viewstate disabled, like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MapControl.ascx.cs"
Inherits="XXX.MapControl" EnableViewState="false" %>
I don't understand why. Anyone care to tell me?
Just from the docs, shouldn't your image map have the different locations in it for the click mapping?
eg:
<asp:ImageMap ID="SaturnImage"
ImageUrl="~/saturn.PNG"
runat="server" OnClick="SaturnImage_Click">
<asp:CircleHotSpot AlternateText="planet" HotSpotMode=PostBack
PostBackValue="planet" Radius=40 X=100 Y=100 />
<asp:CircleHotSpot HotSpotMode=Inactive
Radius=60 X=100 Y=100 />
<asp:CircleHotSpot AlternateText="rings" HotSpotMode=PostBack
PostBackValue="rings" Radius=80 X=100 Y=100 />
</asp:ImageMap>
Because I'm assuming with ImageMap that when you click on it it only does the postback if you click on a part which is set up to be clicked. It shouldn't generated a clicked event if none of the mapped parts are clicked on.

Categories