Search code examples
c#asp.netgridviewevent-handlingreusability

Add remote method to GridView event


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

Solution

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