[转]在DataGrid中动态创建服务器端控件

动态创建服务器端控件在DataGrid的ItemDataBound事件中实现:

private void MyGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
 // e.Item 就是 DataGrid 中的行
 if(e.Item.ItemIndex>=0) // DataGrid 有页眉的情况则从第一行开始创建
 {
  // 定义一个新的 LinkButton 对象
  LinkButton MyButton = new LinkButton();
  MyButton.Text = "查看";
  MyButton.ID = "MyButton";
  MyButton.Click += new System.EventHandler(this.MyButton_Click); // 为控件绑定事件
  
  e.Item.Cells[0].Controls.Add(MyButton); // 在 DataGrid 的第 e.Item.ItemIndex 行的第1个单元格中创建 LinkButton
 }
}

动态创建的控件的事件:

private void MyButton_Click(object sender, System.EventArgs e)
{
 LinkButton lb = (LinkButton)sender; // 取触发事件的 LinkButton 对象
 TableCell cell = (TableCell)lb.Parent; // 取触发事件的 LinkButton 对象所在的单元格
 DataGridItem item = (DataGridItem)cell.Parent; // 触发事件的 LinkButton 对象所在的单元格所在的行
 
 // 具体的事件功能代码,此处省略  
}

需要注意的事项:

private void Page_Load(object sender, System.EventArgs e)
{
 // 绑定 DataGrid 的代码不能放在if (!Page.IsPostBack) 中
 // 因为执行页面代码时首先执行 Page_Load 代码段,然后才执行控件事件代码段
 // 触发动态创建的控件的事件后,回发时控件必须存在
 // 如果绑定代码只是初次加载才执行,则回发时动态创建的控件就不再存在,所以不能响应相应的事件
}

 

 

 

=========================================================

 

            LinkButton lb = (LinkButton)sender; //取得触发触发的LinkButton
            TableCell cell = (TableCell)lb.Parent; //取得触发的LinkButton对象所在的单元格
            GridViewRow item = (GridViewRow)cell.Parent; //取得触发的LinkButton对象所在的行

            HiddenField huzhuID = (HiddenField)item.FindControl("hfd_huzhuIDs"); //取得储存数据的隐藏控件

 

posted @ 2009-11-04 20:30  适渊  阅读(291)  评论(0编辑  收藏  举报