onserverclick wont trigger the event - c#

Nothing works, The button doesn't trigger the event
code of button:
<input type="button" id="regBtn" runat="server" onserverclick="RegClick"/>
script code:
<script runat="server">
void RegClick(object sender, EventArgs e)
{
regBtn.Value += "a";
}
</script>

If you use ASP.Net Web Form, you want to use Service Control whenever posting back to server. It will go through Life Cycle Events, and trigger the appropriate event correctly.
<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click"/>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
SubmitButton.Text += "a";
}

Related

CustomValidator firing but not not preventing postback in ASP.NET

I am using a CustomValidator in ASP.NET as follows.
<asp:CustomValidator ID="AnswerCV" runat="server" ForeColor="Red"
ValidateEmptyText="True" ValidationGroup="test"
OnServerValidate="CustomValidation" ControlToValidate="TextBox1" Enabled="True"
ErrorMessage="You must fill in the text box.">
</asp:CustomValidator>
<asp:TextBox ID="TextBox1" ValidationGroup="test" runat="server">
</asp:TextBox>
<asp:Button runat="server" Id="Button" CausesValidation="True" ValidationGroup="test"
OnClick="Button_Click" />
In the code behind I have
protected void CustomValidation(object sender, ServerValidateEventArgs e)
{
MessageBox.Show("It is firing!!!");
if (string.IsNullOrEmpty(TextBox1.Text))
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}
}
And the button click method is as follows
protected void Button_Click(object sender, EventArgs e)
{
MessageBox.Show("I should not have fired.");
}
The CustomValidation method fires but the Button_Click method fires after that and then the "You must fill in the text box." error message displays. How do I prevent the Button_Click method from firing, when the text box is empty the validation is failing and triggering the error message, but after the Button_click method has fired?
The stackoverflow page here offered other solutions which I have implemented but still the Button_Click method fires.
Aside: And the client side solutions I can not use as I am dynamically going to add code in the Init() method that enables and disables the CustomValidator via a CheckedChanged event in only certain Radio Buttons. End Of Aside
I have also tried the CustomValidator without the OnServerValidate method and I have tried returning a boolean of false from the CustomValidation method cause a syntax error.
protected void Button_Click(object sender, EventArgs e)
{
if (IsValid)
{
Response.Write(" alert ('I should not have fired'); ");
}
}
Please add one if condition in Button_Click Event
protected void Button_Click(object sender, EventArgs e)
{
if (IsValid)
{
Response.Write("<script> alert ('I should not have fired');
</script>");
}
}

Use commandeventargs to a HTML Button control

I have a HTML control ie. Button. PFB Snippet
<button type="button" id="Button7" onserverclick="btnSave_OnClick"
runat="server" commandname="SaveNext">
Next
</button>
I am calling a same server side method from 2 different Button. I need to validate which button is clicked using CommandName in method.
Code behind:
protected void btnSave_OnClick(object sender, EventArgs e)
{
}
The problem is EventArgs e does not have CommandName . I changed method parameter to commandeventargs e which gives error as it requires EventArgs e
I am not preferring to change the HTML control to a asp:button.
Please suggest.
In the server-side event handler, you can retrieve the CommandName from the attributes of the button:
protected void btnSave_OnClick(object sender, EventArgs e)
{
HtmlButton btn = sender as HtmlButton;
string commandName = btn.Attributes["CommandName"];
...
}

asp.net keeps on calling a function in page_load

I've a form (mainpage.aspx), on which there's a button called 'Cancel'. Here's the code for the button:
<asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CssClass="btn btn-default" OnClick="btnCancel_Click" />
and the called function
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("EventList.aspx");
}
So as you can see, what the button do is simple. Just go to another page. But it seems here that doesn't happen. Every time I click the Cancel button, first it will try to load the code
Response.Redirect("EventList.aspx");
but then somehow it will try to execute the codes below:
if (hdnEventId.Value != "" && hdnEventId.Value != "0")
{
LoadEvent();
}
I know this because I put a breakpoint on Response.Redirect("EventList.aspx"); and after that I step into the code above
btw the codes above are located inside
protected void Page_Load(object sender, EventArgs e)
inside the file mainpage.aspx.cs
That's because Page_Load is called on any postback and you're actually doing a postback by clicking Cancel. The solution is to wrap your non-postback specific code in a IsPostBack check:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (hdnEventId.Value != "" && hdnEventId.Value != "0")
{
LoadEvent();
}
}
}

How to force a full postback on a button created in code behind and displayed in an UpdatePanel

I am using an asp.net UpdatePanel that contains Button 1. On Button1 click, a string is created in code behind then sent back to the updatePanel. That string contains Button2 that should fire a postback to execute Button2_Click function. Unfortunately I haven't been able to execute a full postback on button 2 yet.
If I add Button2 as a PostBackTrigger control in the UpdatePanel on my aspx page I get an error that the control (Button2) is not found. This makes sense cause Buton2 is created by clicking Button1 in code behind and is not available on page load.
I'm trying to RegisterPostBackControl(Button2) on page load but again I get an error that Button2 doesn't exist in the current context.
Any help would be highly appreciated.
ASPX page
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<fieldset>
<div runat="server" id="DIV1">Testing...<br /></div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" clientidmode="static"/>
<div runat="server" id="DIV2"></div>
<asp:Label ID="DIV2_LABEL" runat="server"></asp:Label>
</fieldset>
</ContentTemplate>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterPostBackControl(Button2);
}
protected void Button1_Click(object sender, EventArgs e)
{
string DIV1_Html;
DIV1_Html= DIV1.InnerHtml;
DIV2.InnerHtml = DIV1_Html;
DIV2.InnerHtml += "<input id='Button2' type='button' value='button' runat='server' OnClick='Button2_Click' />";
}
protected void Button2_Click(object sender, EventArgs e)
{
DIV2_LABEL.Text = "Testing button2";
}
EDIT
Based on the advice below, I've added the button as follows:
Instead of:
DIV2.InnerHtml += "<input id='Button2' type='button' value='button' runat='server' OnClick='Button2_Click' />";
I've amended the code as follows:
Button Button2 = new Button();
Button2.Text = "Add";
Button2.Click += new EventHandler(Button2_Click);
PostBackTrigger pTrigger = new System.Web.UI.PostBackTrigger() { ControlID = Button2.ID };
UpdatePanel1.Triggers.Add(pTrigger);
DIV2.Controls.Add(Button2);
BUT I'm still missing something because Button2_Click function is not fired when I click on the new button with NO error. ?????
Since your Button2 is created in client-side, It's ID is not recognized by the updatePanel1.
You can create Button2 dynamically like this:
Button button2 = new Button();
PostBackTrigger pTrigger = new System.Web.UI.PostBackTrigger() { ControlID = button2.ID };
updatePanel1.Triggers.Add(pTrigger);
DIV2.Controls.Add(button2);
UPDATE: Here is a little sample that you can use:
public partial class WebForm1 : System.Web.UI.Page
{
private bool ShowButton2()
{
return ViewState["createButton"] == null ? false : (bool)ViewState["createButton"];
}
protected void Page_Load(object sender, EventArgs e)
{
if (ShowButton2())
CreateButton();
}
void CreateButton()
{
Button Button2 = new Button();
Button2.Text = "Add";
Button2.ID = "button2";
Button2.Click += Button2_Click;
PostBackTrigger pTrigger = new System.Web.UI.PostBackTrigger() { ControlID = Button2.ID };
updatePanel1.Triggers.Add(pTrigger);
DIV2.Controls.Add(Button2);
}
void Button2_Click(object sender, EventArgs e)
{
}
protected void button1_Click(object sender, EventArgs e)
{
if (!ShowButton2())
{
ViewState["createButton"] = true;
CreateButton();
}
}
}
The view state is a flag for showing Button2 of course.
There is a property on the button called OnClientClick, you can use that to call a javascript which then navigate to your page.
Example:
In your apsx page
<script type="javascript">
function reloadPage() {
window.location.href = '...';
}
In your code behind
DIV2.InnerHtml += "<input id='Button2' type='button' value='button' OnClick='ReloadPage()' />";

how to Call cs function from html button

Html Button
<input id="Button1" type="button" value="button" runat="server"/>
.cs file:
public void display()
{
Response.Redirect("default.aspx");
}
How to call the display function which is in .cs file from html button click
Use a <asp:button> instead and just bind the click event in the designer.
This will generate an input in the actual html.
In your codebehind file use the following:
protected void Page_PreInit(object sender, EventArgs e)
{
Button1.ServerClick += display;
}
And change your display method signature to:
private void display(object sender, EventArgs e)
{
Response.Redirect("default.aspx");
}

Categories

Resources