Add remote method to GridView event - c#

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

Related

ASP.NET C# Set OnSelectedIndexChanged from Code Behind

Im trying to set the SelectedIndexChanged from the code behind of a Web Forms application. I have a variable amount of dropdowns being added onto the page from the database and need a method to trigger each time one of the dropdowns change.
Im currently trying:
ddlProductCause.SelectedIndexChanged += new EventHandler(ddlProductCause_Changed);
ddlProductCause.ID = "ddlProductCause_" + row["item_id"].ToString();
ddlProductCause.AutoPostBack = true;
and...
public void ddlProductCause_Changed(object sender, CommandEventArgs e)
{
// do stuff
}
But I have no luck.
Any ideas?
Event Argument may cause this, use EventArgs
protected void ddlProductCause_Changed(object sender, EventArgs e){
//to get id
DropDownList ddl=sender as DropDownList;
//ddl.Id <---Access property like this.
}

Button click event error

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.

Button.OnClientClick question

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

How do I call an event method in C#?

When I create buttons in C#, it creates private void button_Click(object sender, EventArgs e) method as well.
How do I call button1_click method from button2_click?
Is it possible?
I am working with Windows Forms.
How do I call button1_click method
from button2_click? Is it possible?
Its wholly possible to invoke the button's click event, but its a bad practice. Move the code from your button into a separate method. For example:
protected void btnDelete_OnClick(object sender, EventArgs e)
{
DeleteItem();
}
private void DeleteItem()
{
// your code here
}
This strategy makes it easy for you to call your code directly without having to invoke any event handlers. Additionally, if you need to pull your code out of your code behind and into a separate class or DLL, you're already two steps ahead of yourself.
// No "sender" or event args
public void button2_click(object sender, EventArgs e)
{
button1_click(null, null);
}
or
// Button2's the sender and event args
public void button2_click(object sender, EventArgs e)
{
button1_click(sender, e);
}
or as Joel pointed out:
// Button1's the sender and Button2's event args
public void button2_click(object sender, EventArgs e)
{
button1_click(this.button1, e);
}
You don't mention whether this is Windows Forms, ASP.NET, or WPF. If this is Windows Forms, another suggestion would be to use the button2.PerformClick() method. I find this to be "cleaner" since you are not directly invoking the event handler.
You can wire up the button events in the ASPX file code.
The button tag will wire the events like this:
<asp:Button Text="Button1" OnClick="Event_handler_name1" />
<asp:Button Text="Button2" OnClick="Event_handler_name1" />
Just wire the OnClick= to your handler method for button1
You can bind same handler for the event of both buttons

EventHandler is null

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.)

Categories