I'm gonna post some more code to show exactly what I'm trying to do,
I'm adding the button using programming code and not markup but the OnClick won't work (giving the following error:
System.Web.UI.WebControls.Button.OnClick(System.EventArgs)' is inaccessible due to its protection level.
Button btnopslaan = new Button();
btnopslaan.Text = "Opslaan";
btnopslaan.ID = "btnOpslaan";
btnopslaan.CssClass = ".opslaan";
btnopslaan.Click += new EventHandler(btnopslaanClick);
btnopslaan_arr[btn_count] = btnopslaan;
add_button(btnopslaan);
protected void btnopslaanClick(object sender, EventArgs e)
{
Debug.WriteLine("success");
}
I just can't find out why this isn't working.
Anyone who can help me out?
You need to use OnClick for server side clicks rather than OnClientClick
Either you can use it inline >
<asp:Button id="btnopslaan" runat="server' OnClick="btnopslaanClick" />
Or in Code behind >
btnopslaan.Click+=new EventHandler(btnopslaanClick);
or you make it a postback call to the server. in your
aspx write:
<asp:Button runat="server" ID="buttonOpslaan" Text="opslaan" ></asp:Button>
codebehind write this:
protected void Page_Init(object sender, EventArgs e)
{
buttonOpslaan.Click += new EventHandler(buttonOpslaan_Click);
}
// mind: this method can be private
void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or handle it with the AutoEventWireUp (recommended) like:
<asp:Button runat="server"
ID="buttonOpslaan"
OnClick="buttonOpslaan_Click"
Text="opslaan" ></asp:Button>
// mind: this method cannot be private, but has to be protected at least.
protected void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or do it completely from code behind:
// note: buttonOpslaan must have an (autoassigned) ID.
protected void Page_Init(object sender, EventArgs e)
{
Button buttonOpslaan = new Button();
buttonOpslaan.Text = "opslaan!";
buttonOpslaan.Click += new EventHandler(buttonOpslaan_Click);
form1.Controls.Add(buttonOpslaan);
}
protected void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or handle it clientside with javascript in your ASPX (it will not reach the server)
<script type="text/javascript">
function buttonOpslaan_Click(){
alert("test");
return false;
}
</script>
<asp:Button runat="server"
ID="buttonOpslaan"
OnClientClick="buttonOpslaan_Click()"
Text="opslaan" ></asp:Button>
Update: (by comments)
if you add the control via an eventhandler (like the onchange event of a dropdownlist), the control is 'lost' on next postback, or even as soon as the Page is send to the client (due to the stateless (there is no mechanism to maintain the state of application) behaviour and lifecycle of .Net).
So simply adding a control once is never going to work.
That means you have to rebuild the control every time a postback occurs. My preferred way to do this is store a list/document somewhere that descrbes what controls must be created each time. Possible locations are, from worse to good (IMHO):
Session
Viewstate
Cache
XML/IO
Database
After all, you are posting "data" to the server (that represents a control) and you want to save that for further use.
If the controls to be created aren't that complex you could implement a Factory Pattern like a WebControlFactory that stores only a few properties in a List or Dictionary, which is read every time to recreate the controls again (and again, and again, and again)
btnopslaanClick should be client side, in the .aspx itself have:
<script type="text/javascript">
function btnopslaanClick() {
alert("success");
}
</script>
btnopslaan.Click+=new EventHandler(btnopslaanClick);
protected void btnopslaanClick(object sender, EventArgs e)
{
Debug.WriteLine("succes");
}
Related
I have an aspx web app that has multiple GridView's with similar methods. My thought was to create a "helper" class that has the reusable methods. My question is what is the best way to utilize those remote class methods?
the frontend doesn't accept the class.method like this:
<asp:GridView runat="server" ID="myGridView" ... OnSorting="myClass.reusableMethod"
Visual Studio didn't give me any compiling errors when I attached the handler on Page_Load, but I did get a runtime error saying the GridView tried to fire the event and it wasn't there.
if (!IsPostBack)
{
myGridView.Sorting += myClass.reusableMethod;
}
The final way I am pretty sure will work, but seems counter-productive. Creating the method on the pages backend like normal but then having the only line being a call to the remote method
public void myGridView_Sorting(object sender, GridViewSortEventArgs e)
{
myClass.reusableMethod();
}
It can be done. First remove the OnSorting event from the GridView.
<asp:GridView ID="myGridView" runat="server" AllowSorting="true">
Then only bind the method outside the IsPostBack check.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//do not bind the event here
}
//but here
myGridView.Sorting += myClass.reusableMethod;
}
Now you can use the Method
public static void reusableMethod(object sender, GridViewSortEventArgs e)
{
GridView gv = sender as GridView;
}
Let say I have this code on Page load of ASP.NET Webform
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = "123";
}
and this is my control in aspx file
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
If I change the textbox data from 123 to 12548 or any thing in the front end and then I click the button
Now in this is my code behind button click event
protected void Button1_Click(object sender, EventArgs e)
{
string s = TextBox1.Text;
}
Now in TextBox1.Text I should be getting 12548 or updated value instead I am getting 123 which I have already set in page load.
Now I want to get the updated value, how may I do it the right way.
Wrap it in a NOT is Postback
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
TextBox1.Text = "123";
}
}
or remove it completely:
protected void Page_Load(object sender, EventArgs e)
{
//not here
}
<asp:TextBox ID="TextBox1" Text="123" runat="server"></asp:TextBox>
Modify the Page_Load as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
TextBox1.Text = "123";
}
}
The problem was this "In ASP.Net every time you cause a postback of any kind, including handling events like button clicks, you're working with a brand new instance of your page class that must be rebuilt from scratch. Any work you've done previously to build the page on the server is gone. That means running the entire page life cycle, including your page load code, and not just the click code.
Every time you perform any event in the front end it will recreate the page and call the pageload method again and the page would be actually reset. To avoid it one should use the following code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
//default code
}
}
Having just added a new button in my web application, I get an error when clicking on it, and I'm wondering if this is related to misplaced code. I will describe what/where I did, briefly. Thanks very much.
In ascx file:
<asp:Button ID="btn_rezerv" runat="server" Text="Reserve film" OnClick="btn_rezerv_Click"/>
In the ascx.cs file:
namespace CinProj.UserControls
{
public partial class FilmsList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
private void PopulateControls()
{
string categId = Request.QueryString["CategID"];
string filmId = Request.QueryString["FilmID"];
....
if (categId != null)
{
.....
}
if (filmId != null)
{
......
Button btn_rezerv = (Button)item.FindControl("btn_rezerv");
}
}
protected void btn_rezerv_Click(object sender, EventArgs e)
{
string fid = Request.QueryString["FilmID"];
ShoppingCartAccess.AddItem(fid);
}
}
}
"Server Error in '/' Application.
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. "
Another problem could be because your PopulateControls method should probably only be called when during the Page Load when it's not a PostBack. I can't tell from above, but to me it looks like it only needs done on Load. Try wrapping that call with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateControls();
}
}
It's likely the result of making some sort of client change that the server doesn't know about. Many times this is the result of changing values in a dropdown in JavaScript, for example.
To fix, you could:
Do away with using JavaScript for said modification
Use an UpdatePanel and add your control to it. If the client needs to make a change, trigger the UpdatePanel's update in order for the control's viewstate to update.
I'm wondering how I could update the querystring of my URL each time I hit the Next button of a Wizard control in order to show the ActiveStepIndex.
Example:
http ://ApplicationName/Default.aspx?Step=1
http ://ApplicationName/Default.aspx?Step=2
http ://ApplicationName/Default.aspx?Step=3
...
Really you probably want to do this when the Active Step changes under any circumstances.
Add a handler for OnActiveStepChanged in your .aspx page:
<asp:Wizard ID="NewWizard" runat="server" ActiveStepIndex="0" OnActiveStepChanged="Wizard_OnActiveStepChanged">
<WizardSteps>
...
</WizardSteps>
</asp:Wizard>
Then, implement your handler:
protected void Wizard_OnActiveStepChanged(object sender, EventArgs e)
{
Request.QueryString.Set("Step",Convert.ToString(NewWizard.ActiveStepIndex));
}
This should work, however I haven't tested this code so I cannot make any kind of guarantee that it will work.
I just found out how to handle this situation.
In HTML:
<body id="body" runat="server">
In code-behind:
protected void wizard_OnActiveStepChanged(object sender, EventArgs e)
{
body.Attributes.Add("onload", "document.location.hash = 'Step" + wizard.ActiveStepIndex + "';");
}
I am trying to raise a click event from User control and handle it on the containing page. The problem I have is, when I click the button 'imgstep1' on the user control, the code behind imgstep1_click event triggers and but the 'btnHandler' event is alway null. Hence it doesnt call the parent event.
Any help on this will be much appreciated.
My User Control Code is :
.ascx code:
<asp:ImageButton ImageUrl="./images/step1.gif"
ID="imgstep1" runat="server"
OnClick="imgstep1_Click"/>
.ascx.cs code :
public delegate void OnImageButtonClick();
public event OnImageButtonClick btnHandler;
protected void imgstep1_Click(object sender, ImageClickEventArgs e)
{
if (btnHandler != null)
btnHandler();
}
.aspx page code:
protected void Page_Load(object sender, EventArgs e)
{
ucStepHdr.btnHandler += new StepsHeader.OnImageButtonClick(ucStepHdr_btnHandler);
}
void ucStepHdr_btnHandler()
{
Response.Write ('test');
}
The code looks simple enough to work correctly. The only reason that btnHandler is null could be because the event registration code in the aspx page is not called.
Is there a post back ? Are you sure you are adding the event EACH TIME the page loads ???
ucStepHdr.btnHandler += new StepsHeader.OnImageButtonClick(ucStepHdr_btnHandler);
If you remove OnClick="imgstep1_Click" and you put this in your ascx.cs
protected ImageButton imgstep1;
protected override void OnInit(EventArgs e)
{
this.imgstep1.Click += new ImageClickEventHandler(imgstep1_Click);
}
Does this method of wiring up your event work?
It looks like it should work... can you step through the code in the debugger, and see what the value of ucStepHdr.btnHandler is as soon as you set it in Page_Load? (Just an aside, traditionally these are set in init rather than load, but this isn't your issue.)