0

I have created user control, in that user control i have one method and I want to call this method in .aspx. I have registered this user control in aspx

For example: Below is method in user control.

public void SetGridData()
{
}

I want to call above method in .aspx.cs file. How can we call this method?

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
Irshad
  • 193
  • 1
  • 7
  • 15
  • 1
    You're opening a can of worms. What exactly is this method being used for? The reason I ask is that it's not returning anything, and, by the method name, it seems to be used to update a grid in the control with data. The problem is that if you invoke this in the aspx, it's probably not going to occur when you want it to - that is, at render time. We probably need a little more information about what you're trying to do. – matt Nov 12 '13 at 14:27
  • @matt I have not pasted here all the code for SetGridData() method. – Irshad Nov 12 '13 at 14:38
  • I understand that. What I'm saying is that if you invoke this method in your ascx file, it is going to occur in the render stage. Take a look at the aspx page life cycle to understand why you probably don't want to do this: http://msdn.microsoft.com/en-us/library/ms178472.ASPX Render occurs _after_ Page_Load and Page_Init. – matt Nov 12 '13 at 14:45
  • @matt, it's just an example, I have to call X Method of User control in to .aspx.cs file. – Irshad Nov 12 '13 at 15:13

2 Answers2

1

Somewhere in the ASPX page's code you should have a reference to the user control object. For example, if the user control is called MyUserControl then somewhere at the class level for the page (possibly in a separate partial class designer file) should be:

protected MyUserControl myUserControl1;

or something similar to that. That's the instance of the user control for the page's class. The page life cycle should instantiate it by the time Page_Load is reached, so from then on you can use that object:

myUserControl1.SetGridData();
David
  • 208,112
  • 36
  • 198
  • 279
  • Is it possible to use and call the method/function of usercontrol before Page_load of aspx page? – user35 Jul 15 '14 at 05:16
  • @user35: That depends on what you need to be available in the page/control when calling the method. The object itself is initialized early in the page life cycle, but certain page life cycle events may not have been invoked: http://stackoverflow.com/a/7335271/328193 – David Jul 15 '14 at 09:58
1

If this is purely an example, then you can call methods in codefiles with the following syntax:

<%= SetGridData(); %>

However, just be aware of the notes I put in the comments above.

matt
  • 9,113
  • 3
  • 44
  • 46