在 DataBind 上选择封装的 DropDownList 中的项目
我有一个复杂的 UserControl
,其主要目的是使用许多属性封装 DropDownList
以进行高级操作。
根据之前设置的属性,在 PreRender
事件上填充列表:
protected void Page_PreRender(object sender, EventArgs e)
{
sourceClient.SelectCommand = this.Property1 ? "exec a" : "exec b";
}
最常用的属性是 ClientID:
[Category("Settings")]
public int ClientID
{
get
{
return Int32.Parse(DropDownList1.SelectedItem.Value);
}
set
{
DropDownList1.Items.FindByValue(value).Selected = true;
}
}
Getter 通常由 SqlDataSources
中的 ControlPameters
调用> 在带有此控件的页面上。
Setter - 来自标记:
。
所以问题是:
为什么 Bind
中的 setter 比 PreRender
更早被调用?并且 DropDownList
为空,项目选择不起作用!如何解决此行为?
Edit1:好的,不是 PreRender
而是 Init
。但是 DropDownList1_DataBinding 仍在属性设置器之后被调用!
I have a complex UserControl
with the main purpose to encapsulate DropDownList
with a number of properties for advanced manipulation.
List is being populated on PreRender
event depending on properties previously were set:
protected void Page_PreRender(object sender, EventArgs e)
{
sourceClient.SelectCommand = this.Property1 ? "exec a" : "exec b";
}
The most used property is ClientID:
[Category("Settings")]
public int ClientID
{
get
{
return Int32.Parse(DropDownList1.SelectedItem.Value);
}
set
{
DropDownList1.Items.FindByValue(value).Selected = true;
}
}
Getter commonly is being called by ControlPameters
in SqlDataSources
on pages with this control.
Setter - from markup: <uc:UserControl1 runat="server" ClientID='<%# Bind("ID") %>' />
.
So the question is:
Why does setter from Bind
is called earlier then PreRender
? And DropDownList
is empty and item selecting doesn't work! How to workaround this behavior?
Edit1: Ok, not PreRender
but Init
. But DropDownList1_DataBinding is still being called after property setter!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
数据绑定始终发生在
PreRender
之前。来自 ASP.Net 页面生命周期:解决您的问题的一种方法是仅处理
DataBinding
事件并预先绑定您的下拉列表(甚至只是在Load
期间执行),而不是等待一直到PreRender
。这将确保 Bind 调用结束时DropDownList
可用。另一种解决方案是仅将控件传递给数据源本身的引用,而不是使用 Bind 调用。然后,它可以在正确的时间以编程方式处理自身绑定 - 您可以加载
DropDownList
,然后获取它的 ID,这一切都在PreRender
期间通过访问数据源进行。DataBinding always occurs before
PreRender
. From ASP.Net Page Lifecycle:One solution to your issue would be to just handle the
DataBinding
event and pre-bind your dropdownlist (or even just do it duringLoad
), rather than waiting all the way untilPreRender
. This would ensure that theDropDownList
was available when the Bind call goes off.Another solution would be to just pass your control a reference to the datasource itself, rather than using a Bind call. Then it could programmatically deal with binding itself at the right times - you could load your
DropDownList
, and then get your ID for it, all duringPreRender
, by accessing the datasource.