这个问题反复在论坛出现,其实这个问题在MSDN上早就有答案
1。英文版:Top Questions about the DataGrid Web Server Control(Mike Pope and Nikhil Kothari)
2。中文版:DataGrid Web 伺服器控制项的常见问题
1。英文版:Top Questions about the DataGrid Web Server Control(Mike Pope and Nikhil Kothari)
2。中文版:DataGrid Web 伺服器控制项的常见问题
可惜,论坛上的风气不太好,你即使给了连接,真正去看的人大概并不多
诀窍是,如果动态添加了列的话,需要在下一次PostBack时,在LoadViewState或更早把这些列重新添加。原因是,在Page类递归调用LoadViewState时,会调用DataGrid的CreateChildControls,而DataGrid的(实际上是它的父类的实现)CreateChildControls会调用DataGrid的CreateControlHierarchy()方法。在其中,DataGrid会根据当前的列的数目构造DataGridItem里的东西,然后从ViewState里恢复原来的数据。如果你没有重新添加你的动态列的话,你的动态列在PostBack后就会消失,更不用谈触发列里的控件的事件了
检验你的动态控件在PostBack后是否还在的一个方法是,加一个按钮看PostBack后的行为
下面是一个简单的测试
1
<html>
2
<body>
3
<form runat="server">
4
<asp:DataGrid id="DataGrid1" runat="server"
5
GridLines="Both" AutoGenerateColumns="false"
6
OnItemCommand="DataGrid1_ItemCommand">
7
<Columns>
8
<asp:ButtonColumn HeaderText="Static Button" Text="Click Me"
9
CommandName="Static"/>
10
<asp:TemplateColumn HeaderText="Data">
11
2
3
4
5
6
7
8
9
10
11