logo

GridView 动态添加 EmptyDataTemplate 的例子

作者:孟宪会 阅读:1956 发表于:2011-01-17 12:19:58

下面代码直接拷贝即可执行。

ASPX 代码
<%@ 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();
    dt.Columns.Add(
new DataColumn("id", typeof(Int32)));
    dt.Columns.Add(
new DataColumn("text", typeof(string)));
    
//DataRow dr;
    //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 EmptyDataTemplate : ITemplate
  {
    private DataControlRowType templateType;
    public EmptyDataTemplate(DataControlRowType type)
    {
      templateType
= type;
    }

    public
void InstantiateIn(System.Web.UI.Control container)
    {
      
switch (templateType)
      {
        
case DataControlRowType.EmptyDataRow:
          TextBox lc
= new TextBox();
          lc.Text
= " EmptyDataTemplate 显示的内容";
          container.Controls.Add(lc);
          
break;
        
default:
          
break;
      }
    }
  }

  protected
void Page_Load(object sender, EventArgs e)
  {
    
if (!IsPostBack)
    {
      EmptyDataTemplate x
= new EmptyDataTemplate(DataControlRowType.EmptyDataRow);
      GridView1.EmptyDataTemplate
= x;
      GridView1.DataSource
= CreateDataSource();//注意这里一定要空数据,不能没有数据绑定。
      GridView1.DataBind();
    }
  }

  protected
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    
//给 EmptyDataTemplate 添加更多的内容
    if (e.Row.RowType == DataControlRowType.EmptyDataRow)
    {
      TableCell c
= new TableCell();
      c.Controls.Add(
new TextBox());
      e.Row.Cells.Add(c);
    }
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  
<title>GridView 动态添加 EmptyDataTemplate 的例子</title>
</head>
<body>
  
<form id="form1" runat="server">
  
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
  
</asp:GridView>
  
</form>
</body>
</html>