1

I have a user control with a method to get data from a database. I'm using a tabbed main page and need to show the same info twice. Is there some way of having 2 user controls on the main page, but having the method called only once and fill the 2 different controls? The method gets data from a db and it seems like a waste to call it twice for the same thing.

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
    }
}

main page

<%@ 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);
Haney
  • 32,775
  • 8
  • 59
  • 68
Karen
  • 21
  • 1

1 Answers1

0

You can't execute a encapsulated method like that. You can do something similar with delegates. If you want to execute a method on all controls of a specific type, another option would be to iterate the controls of the tab page, similar to:

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

Or more compact using linq.

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

Or using a for each delegate

Parent.Controls.OfType<MyControlType>.ForEach(p => PerformTask());
Ross Bush
  • 14,648
  • 2
  • 32
  • 55
  • But won't you still perform task multiple times? Meaning I'd still have to hit up the database for each control? Or in my case, 5 times per control. – Karen Dec 21 '18 at 13:54
  • If that is your main concern then you need to change the way the control pulls data, separation of concern, if you will. If you want to hit the database only once then you will need to abstract the data access methods outside of your control. Can't you have each control unaware of where the data is coming from but still have access to the data via a public method or property? – Ross Bush Dec 21 '18 at 13:58