Search code examples
c#asp.netdynamic-controls

Passing dynamic control as argument to user defined method in c#


My problem is very straight forward. I am using asp.net with c#.

In my page I have many controls like DropDownList, GridView, Repeater etc.

And in some condition I want to reset the control as

DropDownList1.DataSource = null;
DropDownList1.DataBind();

What I want , I like to build a common Method for resetting all the controls, like:

void SomeMethod(Template T)
{
    T.DataSource = null;
    T.DataBind();
}

Here the T can be any of the above mentioned asp controls.

I heard that this can be possible using Template Type, but I have no idea HOW!!!

So please suggest the solution.


Solution

  • You are confusing how generic methods work in C#. I do not think generic methods apply here. You can read up on how (and when) to utilize them here: https://msdn.microsoft.com/en-us/library/twcad0zb.aspx

    As for your particular case, it seems that most controls that support data binding are derived from BaseDataBoundControl. The simplest solution would be to create a method that accepts BaseDataBoundControl as a parameter like so:

    void SomeMethod(BaseDataBoundControl control)
    {
        control.DataSource = null;
        control.DataBind();
    }
    

    One exception that I see from your question is the Repeater. Because it doesn't inherit from BaseDataBoundControl I'd implement an overloaded method that accepts the Repeater class as a parameter.

    void SomeMethod(Repeater control)
    {
        control.DataSource = null;
        control.DataBind();
    }
    

    The result is two simple methods that have the same usage from elsewhere in your code, no matter if you operate on types derived from BaseDataBoundControl or a Repeater class.