开发者

asp.net vb user control raising an event on the calling page

i'm trying to learn about user controls. I created a user control that has a textbox and a button. What i'd like to be able to do is when i click开发者_如何学编程 the button in the user control, populate a label in the aspx page. I understand that i could just have a button on the page that uses some properties on the user control to get that information.. but i'd like to know how to do it with the button the user control.. the reason for this is the button is just an example.. a learning tool. if i can get this working, i'd likely be putting thing in the user control that might require this kind of passing information. Anyway.. i've found some c# examples that i tried to get working as vb.. but once started getting into the delegates and events.. well.. it made me turn to this post.

anyway.. hopefully someone can lend a hand.


See if this tutorial can help. The best way to do this is definitely to wire up an event, which isn't nearly as hard as you think. The basics are:

1. Define an event in your control class:

Public Event MyEvent as System.EventHandler

2. Raise the event in a sub or function of your control class:

RaiseEvent MyEvent(Me, New EventArgs())

3. Handle the event on the page that contains your control:

Protected Sub MyControl_MyEvent(ByVal sender As Object, ByVal e As EventArgs) Handles MyControl.MyEvent
    'Do stuff here
End Sub


I believe what you would want to do is to have your UserControl raise an event. This MSDN article explains how to raise events and has VB examples. Then your page can subscribe to the event that your UserControl raises and set whatever values you need to set. It might be best to expose some of your UserControl fields (i.e. TextBoxes, etc.) as public properties so they're accessible from the subscribed control.


The problem is that if you make the usercontrol dependent on it's parent page, it's no longer portable, and you've defeated the purpose of making it into a usercontrol in the first place.

This is probably why you're running across delegates and whatnot in any examples - people are trying to remove the dependency on the parent page by allowing the usercontrol to call a passed-in method, instead of directly setting the label in the parent page.

If this is just for practice, you'd be better off pressing a button on the parent page to set a label in the usercontrol, rather than the other way around. The way you're doing it now is not a good design and should be avoided for real applications.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜