开发者

Call UserControl method from Its parent page

I got an approach like this to call an Parent Page method from its User Control.This "DisplayMessage" function simply accepts a string variable message and displays it on the screen. In the user control I have placed a textbox and a button. On the click event of the Button I am calling the Parent Page method we discussed above using Reflection and passing the value of the textbox to the method and then the method is invoked and the message is displayed on the screen.

Parent Page:

public void DisplayMessage(string message)
{
   Response.Write(message);
}

User Control:

protected void btnSend_Click(object sender, EventArgs e)
{
    this.Page.GetType().InvokeMember("DisplayMessage",System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { txtMessage.Text });
}

It works fine for me.

Now what I need is, I have to call a method 开发者_开发百科which exists in UserControl from its parent page.

Please suggest me. Thanks in Advance.


Whatever you set the ID="" attribute to when you put the control on the page is the variable name you can use to reference it from within the page.

So if your page looks like this:

<my:UserControl runat="server" ID="myControl" />

Then you can just do:

myControl.MyControlMethod()

The method being invoked in the user control from the parent must be public. If it's private or protected, the method can't be called from the parent.

Also, instead of invoking page functions via reflection, you might be better off using events.


this.Page will give you a reference to the page object.

If you implement the DisplayMessage in a base page and then inherit from that.

you could cast this.Page as BasePage and then call the method that way :)

if(this.Page is BasePage)
{
   BasePage bs = this.Page as BasePage

   bs.DisplayMessage(....)   
}


I guess I found the most easiest way to do it

Just pass the reference of the parent in the constructor of the user control.

this.animationControl = new VideoEditor.AnimationControl(this);

And In the constructor of user control save the reference of parent form in local variable

public AnimationControl(Form1 form)
{
        _form1 = form;
        // other initialization stuff
}

Now access anything from parent class through this local variable '_form1'

Example

_form1.MessageFromAnimationControl(choosenAnim);

access parents variable/methods in child or send child's variables to parent.

I hope it will help someone :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜