Search code examples
c#asp.netgridviewmethodsreusability

Reusable GridView Method


I have a page with multiple gridviews on it. All the gridviews have gridview methods that only vary by the gridview name. Is there a way to have a reusable method and run the code on the calling gridview?

For example, in both gridview1 and gridview2's RowCancelingEdit method both gridviews would have a line of:

[respectivegridview].EditIndex = -1;

The 'this' keyword is pulling the page class and not a gridview so I am not sure if/how to capture which gridview fired the method if I put something like:

OnRowCancelingEdit="gridviews_RowCancelingEdit"

in both gridview1 and gridview2's attributes


Solution

  • If the method is an event handler or if you send the sender object to the method then the gridview can be pulled out by casting the sender to a DataGridView object.

    private void datagridview_edit(object sender, EventArgs e)
    {
        ((DataGridView)sender).EditIndex = -1;
    }