1

我有一个用户控件,其中包含从数据库获取数据的方法。我正在使用选项卡式主页,需要两次显示相同的信息。是否有某种方法可以在主页上拥有 2 个用户控件,但只调用一次该方法并填充 2 个不同的控件?该方法从数据库中获取数据,为同一件事调用两次似乎是一种浪费。

public partial class control : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public void bindcontrol(int id, string pie)
    {
        //get info from database and bind it to a gridview
    }
}

主页

<%@ Register TagPrefix="z" TagName="zz" Src="control.ascx" %>

 <div role="tabpanel" class="tab-pane" id="passport">
                    <z:zz ID="ctrl1" runat="server" />
 </div>
 <div role="tabpanel" class="tab-pane" id="passport">
                    <z:zz ID="ctrl2" runat="server" />
</div>

//code behind - which is what I'm trying to avoid:
 ctrl1.bindSummary(id, strPIE);
 ctrl2.bindSummary(id, strPIE);
4

1 回答 1

0

您不能执行这样的封装方法。你可以对代表做类似的事情。如果要对特定类型的所有控件执行方法,另一种选择是迭代选项卡页的控件,类似于:

  foreach(WebControl c in MyTabPage.Controls)
  {
     if(c is MyControlType)
     {
       ((MyControlType)c).PerformTask();//Cast to your type to call method on type
     }   
  }

或者使用 linq 更紧凑。

foreach(WebControl control in Parent.Controls.OfType<MyControlType>)
    ((MyControlType)c).PerformTask();

或为每个代表使用

Parent.Controls.OfType<MyControlType>.ForEach(p => PerformTask());
于 2018-12-20T18:15:28.733 回答