这个问题反复在论坛出现,其实这个问题在MSDN上早就有答案
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给静态DataGrid动态添加列的问题<html>
 2给静态DataGrid动态添加列的问题<body>
 3给静态DataGrid动态添加列的问题<form runat="server">
 4给静态DataGrid动态添加列的问题<asp:DataGrid id="DataGrid1" runat="server" 
 5给静态DataGrid动态添加列的问题GridLines="Both" AutoGenerateColumns="false"
 6给静态DataGrid动态添加列的问题OnItemCommand="DataGrid1_ItemCommand">
 7给静态DataGrid动态添加列的问题 <Columns>
 8给静态DataGrid动态添加列的问题 <asp:ButtonColumn HeaderText="Static Button" Text="Click Me" 
 9给静态DataGrid动态添加列的问题 CommandName="Static"/>
10给静态DataGrid动态添加列的问题 <asp:TemplateColumn HeaderText="Data">
11

相关文章:

  • 2021-12-09
  • 2021-07-15
  • 2022-03-04
  • 2021-11-18
  • 2022-12-23
  • 2021-05-20
  • 2022-12-23
  • 2021-08-31
猜你喜欢
  • 2021-05-28
  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
  • 2021-04-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案