动态模板列更新操作和分页

<%@ 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);   
  }//这里没有为这个下拉框进行数据绑定,在DataGrid1的ItemDataBound中进行了这个操作
 }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在layui中,可以使用table模块来实现表格的动态分页。下面是一个简单的示例: HTML代码: ```html <table id="demo" lay-filter="test"></table> ``` JavaScript代码: ```javascript layui.use(['table'], function(){ var table = layui.table; //执行渲染 table.render({ elem: '#demo', //绑定元素 url: '/api/data', //数据接口 page: true, //开启分页 cols: [[ //表头 {field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'}, {field: 'username', title: '用户名', width:120}, {field: 'email', title: '邮箱', width:150}, {field: 'sex', title: '性别', width:80, sort: true}, {field: 'city', title: '城市', width:100}, {field: 'sign', title: '签名', width:200}, {field: 'experience', title: '积分', width:80, sort: true}, {field: 'score', title: '评分', width:80, sort: true}, {field: 'classify', title: '职业', width:100}, {field: 'wealth', title: '财富', width:135, sort: true}, {fixed: 'right', title:'操作', toolbar: '#barDemo', width:150} ]] }); }); ``` 在上面的示例代码中,我们使用了table模块的render方法来渲染表格。其中,url参数指定了数据接口的地址,page参数开启了分页功能,cols参数定义了表头和数据。在实际应用中,你需要根据自己的情况修改这些参数。 另外,如果你需要在表格中添加操作,可以使用laytpl模块来实现。下面是一个示例代码: HTML代码: ```html <script type="text/html" id="barDemo"> <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a> <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a> </script> ``` JavaScript代码: ```javascript layui.use(['table', 'laytpl'], function(){ var table = layui.table, laytpl = layui.laytpl; //执行渲染 table.render({ elem: '#demo', //绑定元素 url: '/api/data', //数据接口 page: true, //开启分页 cols: [[ //表头 {field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'}, {field: 'username', title: '用户名', width:120}, {field: 'email', title: '邮箱', width:150}, {field: 'sex', title: '性别', width:80, sort: true}, {field: 'city', title: '城市', width:100}, {field: 'sign', title: '签名', width:200}, {field: 'experience', title: '积分', width:80, sort: true}, {field: 'score', title: '评分', width:80, sort: true}, {field: 'classify', title: '职业', width:100}, {field: 'wealth', title: '财富', width:135, sort: true}, {fixed: 'right', title:'操作', toolbar: '#barDemo', width:150} ]] }); //监听工具条 table.on('tool(test)', function(obj){ var data = obj.data; if(obj.event === 'del'){ layer.confirm('真的删除行么', function(index){ obj.del(); layer.close(index); }); } else if(obj.event === 'edit'){ laytpl($('#editTpl').html()).render(data, function(html){ layer.open({ type: 1, title: '编辑用户', content: html, area: ['400px', '300px'], btn: ['保存', '取消'], yes: function(index, layero){ //保存操作 layer.close(index); }, btn2: function(index, layero){ //取消操作 } }); }); } }); }); ``` 在上面的示例代码中,我们定义了一个id为barDemo的模板,用来渲染操作。在监听工具条事件时,我们可以通过laytpl模块来渲染编辑弹窗的内容。 ### 回答2: Layui是一个基于JavaScript的前端框架,可以用来构建现代化的Web界面。在Layui中,可以很方便地实现表格的动态分页。 首先,我们需要引入Layui的相关资源文件,如css和js文件。接着,在HTML中创建一个包含表格的容器,比如一个div标签,并给它一个唯一的id。 然后,在JavaScript中,通过调用Layui的table模块的render方法来渲染表格。在调用render方法时,需要指定表格的选择器和相关配置参数。 在配置参数中,我们需要设置表格的数据接口,即从服务器端获取表格数据的URL地址。通过设置URL地址,Layui会自动发送一个GET请求到该URL,并获取服务器返回的数据。 在服务器端,我们需要根据请求的参数,比如当前页码和每页显示的数据量,从数据库中获取对应的数据,并返回给客户端。 Layui还提供了一些其他的配置参数,比如设置表格的信息、每页显示的数据量、是否显示分页等。我们可以根据需求来定制这些参数。 当表格数据获取到之后,Layui会将数据渲染到表格中,并自动根据配置参数显示分页器。通过点击分页器上的页码,可以切换表格的当前页。 总结起来,通过Layui的table模块的render方法,我们可以很方便地实现表格的动态分页。通过设置相关配置参数,我们可以自定义表格的信息、每页显示的数据量等。这样,我们可以在前端页面中通过分页器来切换表格的不同页码,从而实现动态分页功能。 ### 回答3: Layui是一款基于HTML5和CSS3的前端框架,它提供了丰富的组件和模块,方便开发人员快速搭建界面。要实现表格动态分页,可以使用Layui提供的表格组件和分页组件。 首先,需要引入Layui的相关文件,包括layui.js、layui.css和lay/modules/table.js等文件。 接着,在HTML中创建一个table元素,并为其加上id属性,例如: ``` <table id="demo" lay-filter="test"></table> ``` 然后,在JavaScript中初始化表格和分页组件,设置相应的参数: ``` layui.use(['table', 'laypage'], function(){ var table = layui.table; var laypage = layui.laypage; // 渲染表格 table.render({ elem: '#demo', url: '/api/data', // 数据接口 page: true, // 开启分页 limit: 10, // 每页显示的条数 cols: [[ // 表头 {field: 'id', title: 'ID', width: 80}, {field: 'name', title: '姓名', width: 120}, {field: 'age', title: '年龄', width: 80}, {field: 'city', title: '城市', width: 150} ]] }); // 监听分页组件 laypage.render({ elem: 'test', count: 100, // 总条数 limit: 10, // 每页显示的条数 curr: location.hash.replace('#!page=', ''), // 获取hash值作为当前页 hash: 'page', // 自定hash值 jump: function(obj, first){ // 首次不执行 if(!first){ // 更新表格数据 table.reload('demo', { where: { page: obj.curr // 更新当前页 } }); } } }); }); ``` 以上代码示例中,url参数指定了获取数据的接口,cols参数定义了表格的,count参数定义了数据总条数,jump回调函数监听了分页组件的变化,当页码改变时,会执行回调函数,并通过table.reload方法重新加载表格数据。 总结起来,要使用Layui实现表格动态分页,需要初始化表格和分页组件,并监听分页组件的变化来重新加载表格数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值