简体   繁体   English

C#ASP.NET绑定控件通过通用方法

[英]C# ASP.NET Binding Controls via Generic Method

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. 我有一些我维护的Web应用程序,我发现自己经常一遍又一遍地编写相同的代码块来将GridView绑定到数据源。 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. 我正在尝试创建一个Generic方法来处理数据绑定,但我无法使用Repeater和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. 这样我就可以定义我的CommandText,然后调用“BindControls(myGridView,cmd)”,而不是每次需要绑定网格时重新输入相同的基本代码块。

The problem is, this doesn't work with Repeaters or DataLists. 问题是,这不适用于Repeater或DataLists。 Each of these controls inherit their respective "DataSource" and "DataBind" methods from different classes. 这些控件中的每一个都从不同的类继承它们各自的“DataSource”和“DataBind”方法。 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. GridView,Datalist和Repeater从BaseDataBoundControl,BaseDataList和Repeater类中获取各自的“DataBind”方法。 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? 或者我最好只为这种方法使用3次重载?

  • Dave 戴夫

What I would try is to set the DataSource property and run the DataBind() method with reflection. 我想尝试的是设置DataSource属性并使用反射运行DataBind()方法。 And not tie the T type to an specific type. 并且不要将T类型绑定到特定类型。

I've done this before too, and creating 3 overloads like you've suggested is absolutely a fine solution. 我之前也做过这个,并且像你建议的那样创建3个重载绝对是一个很好的解决方案。 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. 现在创建一个像你想象的“Bindable”界面为时已晚,需要在设计对象时实现接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM