日期:2010-04-06  浏览次数:20399 次

  动态添加列,关键是实现 ITemplate.InstantiateIn 方法。下面是一个添加 GridView 模板列的例子。

  C#代码

<%...@ Page Language="C#" %>
<%...@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">...
  ICollection CreateDataSource()
  ...{
    DataTable dt = new DataTable();
    DataRow dr;
    dt.Columns.Add(new DataColumn("id", typeof(Int32)));
    dt.Columns.Add(new DataColumn("text", typeof(string)));
    for (int i = 0; i < 6; i++)
    ...{
      dr = dt.NewRow();
      dr[0] = i;
      dr[1] = "列表项目 " + i.ToString();
      dt.Rows.Add(dr);
    }
    DataView dv = new DataView(dt);
    return dv;
  }

  public class GridViewTemplate : ITemplate
  ...{
    private DataControlRowType templateType;
    private string columnName;

    public GridViewTemplate( DataControlRowType type, string colname )
    ...{
      templateType = type;
      columnName = colname;
    }

    public void InstantiateIn( System.Web.UI.Control container )
    ...{
      switch (templateType)
      ...{
        case DataControlRowType.Header:
          Literal lc = new Literal();
          lc.Text = columnName;         
          container.Controls.Add(lc);         
          break;
        case DataControlRowType.DataRow:
          DropDownList drr = new DropDownList();
          drr.ID = "dropdown";
          drr.AppendDataBoundItems = true;
          drr.Items.Add(new ListItem("-----请选择------",""));
          drr.Items.Add(new ListItem("AA", "a"));
          drr.Items.Add(new ListItem("BB", "b"));
          drr.Items.Add(new ListItem("CC", "c"));
      &nb