从子控件到父控件共享价值
我对此比较陌生,但这是我的问题。
在 asp.net 中,我有一个父控件和一个子控件。在子控件中,我有一个下拉列表。根据下拉列表的选定值,我想在父控件中切换面板的可见性。例如,如果我选择在子控件下拉列表中显示,我需要将 true 传递给父控件以使面板可见,反之亦然。我该怎么做呢。我读过这可以通过事件处理来完成,并且看到了某些场景,但我对此并不清楚。请帮忙!
谢谢。
I am relatively new to this, but here is my problem.
In asp.net, I have a parent and a child control. Within the child control I have a dropdown list. Based on dropdown list's selected value I would like to toggle Visibility of Panel in parent control. For instance if I select Show in child control dropdown list, I need to pass true to parent control to make Panel visible and vice versa. How should I do that. I have read that can be done via the event handling and have seen certain scenarios but I am not clear on that. Please help!
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
引发您的父控件侦听的事件。
在父控件的代码隐藏中,创建子控件类型的对象。类似于:
然后在子控件中,定义一个事件
在 DropDownList 的 OnIndexChanged 事件中,完成处理后,引发事件:
在父控件中,连接该事件。 Page_Init 很好
仍然在父控件中,定义您的方法
应该是让它工作所需的全部!
Raise an event that your parent control listens for.
In the code behind for your parent control, create an object of the type of your child control. Something like:
Then in the child control, define an event
In the OnIndexChanged event of your DropDownList, after you do your processing, raise your event:
In your parent control, wire up the event. Page_Init is good
Still in the parent control, define your method
Should be all you need to get it working!
一种方法是公开下拉列表(公共),并在父控件中检查子控件下拉列表,以查看它是否应该在页面加载时显示或隐藏面板。这是否有效取决于页面生命周期。
另一种方法是在发生更改事件时将下拉值存储在 ViewState 中。这样父控件就可以读取 ViewState 参数。
如果可能的话,你绝对应该选择第一个选项。
One way to do it is to expose the dropdown list (public) and in your parent control check the child controls dropdown to see if it should show or hide the panel on page load. If this works or not depends a little on the page lifecycle.
Another way to do it is to store the drop-down value in ViewState on the change event. That way the ViewState parameter can be read by the parent control.
If possible you should definitely go for the first option.
基本上,您只需要订阅
SelectedIndexChanged
事件并处理它。当所选项目发生更改时会触发该事件。请注意,您应该允许下拉控件上的自动回发,以确保在用户更改下拉列表的值后立即触发该事件。在 ASPX 文件中:
如果您在代码隐藏中创建控件,请在创建控件后进行订阅,如下所示:
然后处理它:
编辑: 另外,请查看更详细的 MSDN 上的示例。请注意,该事件是在
DropDownList
的祖先“ListControl”中声明的。Basically, you just need to subscribe to the
SelectedIndexChanged
event and handle it. The event is fired when the selected item was changed. Note that you should allow auto-postback on the drop down control to make sure the event is fired just after the user changed the drop down's value.In the ASPX file:
<asp:DropDownList … OnSelectedIndexChanged="OnDropDownChanged">…</asp:dropDownList>
In case you are creating the control in the code-behind, subscribe after creating the control like this:
And then handle it:
EDIT: Also, have a look on a more elaborate example on MSDN. Note that the event is declared in
DropDownList
's ancestor 'ListControl'.