处理选择下拉列表中的第一个项目和后续事件
我的 aspx 页面上有一个下拉列表,我将其绑定到数据源。我注意到选择第一个项目并没有触发 selectedindexchanged 事件。开始寻找答案时,我发现最常见的做法是将第一个项目放入 ddl 中,可以是空字符串,也可以是“---Select---”之类的内容。
太棒了,成功了。但后来我注意到它仍然触发了我的 Page_Load 事件。在我的 Page_Load 事件中,我检查回发。如果不是,它会数据绑定到转发器和 ddl。因此,选择 ddl 中的第一项会跳过与中继器和 ddl 的数据绑定,最终得到一个空白页面。
我首先认为我可以通过启用视图状态来解决这个问题,但是可惜。在这里和那里之后,我将以下内容放入我的代码中,但我真的觉得它看起来很糟糕。有人有更好的主意吗?
if (!IsPostBack || RacesDropDownList.SelectedIndex == 0)
{
PopulateControls();
}
I have a dropdownlist on my aspx page, which I bind to a datasource. I noticed that selecting the first item didn't fire the selectedindexchanged event. Setting out to look for an answer I found that the most common thing to do was put a first item in the ddl, either with an empty string or with something like "---Select---".
Great, that worked. But then I noticed that it still fired my Page_Load event. In my Page_Load event I check for a postback. If its not, it databinds to a repeater and the ddl. So what happens is that selecting the first item in the ddl skips the databinding to the repeater and ddl, and I end up with a blank page.
I first thought I could fix this by enabling viewstate, but alas. After here and there, I put the following in my code, but I really feel it looks hacky. Does anyone have a better idea?
if (!IsPostBack || RacesDropDownList.SelectedIndex == 0)
{
PopulateControls();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您需要启用视图状态。当没有发生回发时,您必须将下拉列表数据绑定到数据源。只需将以下内容添加到 Page_Load 事件中即可完成此操作:
请记住,默认的 selectedindex 始终为 0,如果它已更改,则会发生回发,因此您的原始代码将由于 !IsPostBack 条件而跳过数据绑定=> '||根本不需要 RacesDropDownList.SelectedIndex == 0' 。
然后,如果在任何事件中您必须刷新列表,通常的解决方案是在事件处理程序中而不是在 Page_Load() 中触发 PopulateControls() 函数。
例如:
我希望这有帮助。
First of all you need viewstate to be enabled. When no postback has happened, then you have to databind the dropdownlist to the datasource. Do it by simply adding the following to the Page_Load event:
Keep in mind, that the default selectedindex is always 0, and if it has changed, then a postback will happen so your original code will already skip the databinding because of the !IsPostBack condition => '|| RacesDropDownList.SelectedIndex == 0' is not needed at all.
Then later, if on any event you have to refresh the list, the usual solution is to fire the PopulateControls() function in the event handler and not in Page_Load().
For example:
I hope this helps.