在什么情况下应该设置动态控件属性?
本文指出应使用 Page_PreInit
到
创建或重新创建动态控件。
例如:
Button button = new Button();
somePanel.Controls.Add(button);
很好。我明白。
但是,它还说:
如果请求是回发,则控件的值还没有 已从视图状态恢复。如果您在此设置控制属性 阶段,其值可能会在下一个事件中被覆盖。
嗯?
这是否意味着我应该做的就是创建按钮,但不设置按钮的任何成员?
例如:
Button button = new Button() { CommandArgument="arg" };
somePanel.Controls.Add(button);
这是否意味着在此事件中设置 CommandArgument
不正确/不推荐/可能会导致错误/意外行为?
假设这是不正确的,这会让我认为人们必须做这样的事情:
protected void Page_PreInit(object sender.....)
{
somePanel.Controls.Add((new Button());
}
protected void Page_Init(object sender.....)
{
foreach(Button button in somePanel.Controls)
button.CommandArgument = "arg";
}
这是正确的方法吗?
最后,在什么情况下应该设置动态控件属性?
This article states that Page_PreInit
should be used to
create or re-create dynamic controls.
For example:
Button button = new Button();
somePanel.Controls.Add(button);
Good. I understand.
However, it also says:
If the request is a postback, the values of the controls have not yet
been restored from view state. If you set a control property at this
stage, its value might be overwritten in the next event.
Huh?
Does this mean that all I should do is create the button, but not set any members of the button?
For example:
Button button = new Button() { CommandArgument="arg" };
somePanel.Controls.Add(button);
Does this mean that setting CommandArgument
in this event is incorrect/not recommended/might cause an error/unexpected behavior?
Assuming it is incorrect, this would lead me to think that one would have to do something like this:
protected void Page_PreInit(object sender.....)
{
somePanel.Controls.Add((new Button());
}
protected void Page_Init(object sender.....)
{
foreach(Button button in somePanel.Controls)
button.CommandArgument = "arg";
}
is this the right way?
Finally, in which event should one set dynamic control properties?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于最后一个问题没有单一的答案,因为根据属性的性质,在特定方法中设置值可能有意义也可能没有意义。
力量是这里的关键词。如果您考虑某些属性可能会随着表单经历各种状态而发生变化,那么您必须小心可能会被覆盖的内容,以及这是否是一件坏事的问题,因为更新后的内容可能会被覆盖。值应该是持久的,在其他情况下,原始值可能更好,例如有人想要将表单重置为其初始状态。
我的建议是进行一些试验和错误,看看什么有效,因为我记得使用动态控件,在某些情况下,正确管理可能很棘手。
There is no single answer for that last question as depending on the nature of the property it may or may not make sense to set a value in a specific method.
Might is the keyword here. If you consider some properties that may change as a form goes through various states then this is where you have to be careful of what may get overwritten as well as the question of whether or not this is a bad thing as it may be that the updated value should persistent and in other cases the original value may be better such as if someone wants to reset the form to its initial state.
My suggestion would be to do some trial and error to see what works as I can remember working with dynamic controls that could be tricky in some me cases to manage properly.