动态模板列更新数据分页的例子

简介: 前台:     WebForm30                                后台: using System; using System.Collections; using System.
  前台:
<%@ Page language="c#" Codebehind="WebForm30.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm30" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm30</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <link href="css.css" rel="stylesheet" type="text/css">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <asp:DataGrid ID="DataGrid1" Runat="server"></asp:DataGrid>
  </form>
 </body>
</HTML>
后台:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace csdn
{
 /// <summary>
 /// WebForm30
的摘要说明。
 /// </summary>
 public class WebForm30 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid DataGrid1;
  
  private void Page_Load(object sender, System.EventArgs e)
  {
   //
在此处放置用户代码以初始化页面
   if(!IsPostBack)
   {
    BindGrid();
   }
   CreateDataGrid();//
进行一些DataGrid的设置
  }
 
  protected void CreateDataGrid()
  { 
   DataGrid1.AutoGenerateColumns=false;//
不启用自动生成列
   DataGrid1.CssClass="border";//
边框样式
   DataGrid1.BorderWidth=0;
   DataGrid1.CellSpacing=1;
   DataGrid1.CellPadding=5;
   DataGrid1.ItemStyle.CssClass="item";//
普通列样式
   DataGrid1.HeaderStyle.CssClass="header";//
头样式
   DataGrid1.PagerStyle.CssClass="header";//
页脚样式
   DataGrid1.DataKeyField="stuid";//
主键字段
   DataGrid1.AllowPaging=true;//
允许分页
   DataGrid1.PageSize=5;//
分页大小
   DataGrid1.PagerStyle.Mode=PagerMode.NumericPages;//
数字形式分页
   EditCommandColumn ecc=new EditCommandColumn();//
更新按钮列
   ecc.ButtonType=ButtonColumnType.PushButton;//
下压按钮
   ecc.EditText="
编辑";
   ecc.CancelText="
取消";
   ecc.UpdateText="
更新";//按钮文字
   DataGrid1.Columns.Add(ecc);//
增加按钮列
   DataGrid1.EditCommand+=new DataGridCommandEventHandler(DataGrid1_EditCommand);
   DataGrid1.UpdateCommand+=new DataGridCommandEventHandler(DataGrid1_UpdateCommand);
   DataGrid1.CancelCommand+=new DataGridCommandEventHandler(DataGrid1_CancelCommand);//
更新、取消、编辑事件注册
   DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(DataGrid1_PageIndexChanged);//
分页事件注册,这里需要注意注册事件代码的位置,不能放到BindGrid()
   SetBind();   //
绑定数据
  }

  protected void BindGrid()
  {   
   TemplateColumn tm=new TemplateColumn();
   tm.ItemTemplate=new ColumnTemplate1();//
普通列
   tm.EditItemTemplate=new ColumnTemplate2();//
编辑列
   tm.HeaderText="
姓名";
   DataGrid1.Columns.AddAt(0,tm);//
在第一列增加第一个模板列
   TemplateColumn tm2=new TemplateColumn();
   tm2.ItemTemplate=new ColumnTemplate3();
   tm2.EditItemTemplate=new ColumnTemplate4();
   tm2.HeaderText="
学院";
   DataGrid1.Columns.AddAt(1,tm2);//
在第二列增加第一个模板列
   DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(DataGrid1_ItemDataBound);//
数据绑定事件注册,这里需要注意注册事件代码的位置
   SetBind();
  }

  protected void SetBind()
  {
   SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
   SqlDataAdapter da=new SqlDataAdapter("select * from stu,dep where stu.studepid=dep.depid",conn);
   DataSet ds=new DataSet();
   da.Fill(ds,"table1");
   this.DataGrid1.DataSource=ds.Tables["table1"];
   this.DataGrid1.DataBind();
  
  }

  private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
   SqlDataAdapter da=new SqlDataAdapter("select * from dep",conn);
   DataSet ds=new DataSet();
   da.Fill(ds,"table1");
   if(e.Item.ItemType==ListItemType.EditItem)
   {
    DropDownList ddl=(DropDownList)e.Item.FindControl("dep");
    ddl.DataSource=ds.Tables["table1"];
    ddl.DataTextField="depname";
    ddl.DataValueField="depid";
    ddl.DataBind();
    ddl.Items.FindByValue(Convert.ToString(DataBinder.Eval(e.Item.DataItem,"depid"))).Selected=true;
   }
  }

  private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   this.DataGrid1.EditItemIndex=e.Item.ItemIndex;
   BindGrid();
  }

  private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   this.DataGrid1.EditItemIndex=-1;
   BindGrid();
  }

  private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   string uid=e.Item.UniqueID+":";//
注意别遗漏冒号
   SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
   SqlCommand comm=new SqlCommand("update stu set stuname=@name,studepid=@depid where stuid=@id",conn);
   SqlParameter parm1=new SqlParameter("@name",SqlDbType.NVarChar,50);
   parm1.Value=Request.Form[uid+"name"].ToString();
   SqlParameter parm2=new SqlParameter("@depid",SqlDbType.Int);
   parm2.Value=Request.Form[uid+"dep"].ToString();;
   SqlParameter parm3=new SqlParameter("@id",SqlDbType.Int);
   parm3.Value=this.DataGrid1.DataKeys[e.Item.ItemIndex];
   comm.Parameters.Add(parm1);
   comm.Parameters.Add(parm2);
   comm.Parameters.Add(parm3);
   conn.Open();
   comm.ExecuteNonQuery();
   conn.Close();
   this.DataGrid1.EditItemIndex=-1;
   BindGrid();   
//
之所以不能采用以前的((TextBox)e.Item.FindControl("name")).Text来取得数据时因为,DataGrid列是动态添加的,根本取不到
  }

  private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
  {
   this.DataGrid1.CurrentPageIndex=e.NewPageIndex;
   BindGrid();
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN:
该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
 
  /// <summary>
  ///
设计器支持所需的方法 - 不要使用代码编辑器修改
  ///
此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion
 }

 public class ColumnTemplate1 : ITemplate
 {
  
  public void InstantiateIn(Control container)      
  {
   LiteralControl l = new LiteralControl();
   l.DataBinding += new EventHandler(this.OnDataBinding);
   container.Controls.Add(l);   
  }

  public void OnDataBinding(object sender, EventArgs e)
  {
   LiteralControl l = (LiteralControl) sender;
   DataGridItem container = (DataGridItem) l.NamingContainer;
   l.Text = ((DataRowView)container.DataItem)["stuname"].ToString();
  }
 }

 public class ColumnTemplate2 : ITemplate
 {
  public void InstantiateIn(Control container)      
  {
   TextBox t = new TextBox();
   t.Width=88;
   t.ID="name";//
需要给一个id,在Request.Form的时候可以取
   t.DataBinding += new EventHandler(this.OnDataBinding);
   container.Controls.Add(t);   
  }

  public void OnDataBinding(object sender, EventArgs e)
  {
   TextBox t= (TextBox) sender;
   DataGridItem container = (DataGridItem) t.NamingContainer;
   t.Text = ((DataRowView)container.DataItem)["stuname"].ToString();//
绑定stuname字段
  }
 }

 public class ColumnTemplate3 : ITemplate
 {
  public void InstantiateIn(Control container)      
  {
   LiteralControl l = new LiteralControl();
   l.DataBinding += new EventHandler(this.OnDataBinding);
   container.Controls.Add(l);   
  }

  public void OnDataBinding(object sender, EventArgs e)
  {
   LiteralControl l = (LiteralControl) sender;
   DataGridItem container = (DataGridItem) l.NamingContainer;
   l.Text = ((DataRowView)container.DataItem)["depname"].ToString();
  }
 }

 public class ColumnTemplate4 : ITemplate
 {
  public void InstantiateIn(Control container)      
  {
   DropDownList dpl = new DropDownList();
   dpl.ID="dep";
   container.Controls.Add(dpl);   
  }//
这里没有为这个下拉框进行数据绑定,在DataGrid1ItemDataBound中进行了这个操作
 }
}

代码比较简单,在代码中有注释简单的解释。
补充2点:(1)这次的DataGrid是在设计生成的,不是上次的运行时,后者会造成更新的紊乱;(2)处于简单,代码中模板列类没有很好的封装,在运用的时候还是应该对字段和模板列类型(ListItemType)进行封装

 

目录
相关文章
|
移动开发 前端开发 Android开发
解决flex布局新旧版本的兼容性写法
最新开发h5的项目用了css的新特性flex布局,遇到了CSS兼容性的问题。在网上找到了如下的解决办法。 我写页面的时候用到过很多的flex布局,觉得非常好用。下面附上一篇不错的flex布局介绍的文章。 Flex 布局教程想了解的可以自己去看看这篇博文,或者自己百度,这里先部多做介绍,我们主要来说一说flex布局的兼容性问题。
930 0
解决flex布局新旧版本的兼容性写法
|
3天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
13天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1292 5
|
12天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1319 87
|
2天前
|
弹性计算 安全 数据安全/隐私保护
2025年阿里云域名备案流程(新手图文详细流程)
本文图文详解阿里云账号注册、服务器租赁、域名购买及备案全流程,涵盖企业实名认证、信息模板创建、域名备案提交与管局审核等关键步骤,助您快速完成网站上线前的准备工作。
179 82
2025年阿里云域名备案流程(新手图文详细流程)