ASP.NET 自定义服务器控件 (GridView)、数据绑定和控件生命周期冲突
我创建了一个自定义服务器控件(继承自 GridView)。
在页面上,GridView 是数据绑定到数据集的,因此我在设计时不知道 GridView 中将出现哪些列。
现在,我想做的是,在 GridView 标题行的每个单元格中添加一个文本框,这些文本框将控制列过滤。 (文本框是使用 GridView OnRowCreated 方法添加的)。
到目前为止一切顺利,文本框出现,并且过滤正在工作。
问题是,每次回发后,文本框的文本值都会丢失。 根据我的实验,这似乎是因为我在页面/控件生命周期中添加文本框太晚了。
如何处理此类问题,我需要在生命周期的早期创建和添加文本框(例如 GridView 的 OnInit),但添加文本框取决于生命周期后期获取的信息?
I have created a Custom Server Control (Inherited from GridView).
On the page, the GridView is DataBound to a DataSet, so I do not know at design time what columns will be present in my GridView.
Now, what I want to do is, to add a textbox in every Cell for the GridView Header row, and those textboxes will control column filtering. (textboxes are added using the GridView OnRowCreated method).
So far so good, the textboxes appear, and the filtering is working.
Problem is, after every postback, the Text value of the textboxes is lost. From my experimentations, this seems to be because I'm adding the textboxes too late in the Page/Control lifecycle.
How does one deal with this type of problem, where I would need to create and add the textboxes early in the Lifecycle (like, the GridView's OnInit), but adding the textboxes is dependant on information that is obtained later in the lifecycle?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不将值存储在 ViewState 中并在回发时读回它们(重新填充文本框)?
Why not store the values in the ViewState and read them back (refill the text boxes) on the postback?
您不必担心文本框的值,只需担心它们的 ID 以及创建它们的时间; 只要您创建并“提供”具有相同数量的文本框及其各自(唯一(!))ID 的页面,控制状态(...嗯...或者可能是视图状态)将处理其余的事情。
您可以使用 Page_Init 和 Page_Load 来执行此操作...Page_Init 是推荐的,但这取决于您的需要。
You don't have to worry about the textbox's values, just their ID and when you create them; control state(...hmmm...or maybe the viewstate) will take care of the rest, as long as you create and "supply" the page with the same number of textboxes and their respective (unique(!)) ID's.
You can do this is both Page_Init and Page_Load...Page_Init is somewhat recommended, but that depend on your needs.
有一个有用的页面: http://msdn.microsoft.com /en-us/library/ms178472.aspx
它特别指出您需要使用 Pre_Init 事件来创建 yout 控件:
There´s a page that would be useful: http://msdn.microsoft.com/en-us/library/ms178472.aspx
It specifically says that you need to use the Pre_Init event to create yout controls: