views:

75

answers:

2

I have a few web applications that I maintain and I find myself very often writing the same block of code over and over again to bind a GridView to a data source. I'm trying to create a Generic method to handle data binding but I'm having trouble getting it to work with Repeaters and DataLists.

Here is the Generic method I have so far:

public void BindControl<T>(T control, SqlCommand sql) where T : System.Web.UI.WebControls.BaseDataBoundControl
    {
        cmd = sql;
        cn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {
            control.DataSource = dr;
            control.DataBind();
        }
        dr.Close();
        cn.Close();
    }

That way I can just define my CommandText then make a call to "BindControls(myGridView, cmd)" instead of retyping this same basic block of code every time I need to bind a grid.

The problem is, this doesn't work with Repeaters or DataLists. Each of these controls inherit their respective "DataSource" and "DataBind" methods from different classes. Someone on another forum suggested that I implement an interface, but I'm not sure how to make that work either.

The GridView, Datalist and Repeater get their respective "DataBind" methods from BaseDataBoundControl, BaseDataList, and Repeater classes. How would I go about creating a single interface to tie them all together? Or am I better off just using 3 overloads for this method?

  • Dave
A: 

What I would try is to set the DataSource property and run the DataBind() method with reflection. And not tie the T type to an specific type.

Francisco Soto
A: 

I've done this before too, and creating 3 overloads like you've suggested is absolutely a fine solution. It's too late to create a "Bindable" interface like you are envisioning, interfaces need to be implemented at the time an object is designed.

Stephen Swensen