datagrid数据表格使用总结

一、加载的css文件

  1. easyui 基本样式: <link href="../easyui/easyui1.5.css" rel="stylesheet" type="text/css" />
  2. easyui 按钮样式:<link href="../easyui/icon.css" rel="stylesheet" type="text/css" />  表单需要进行编辑时按钮所需样式

二、加载的js文件

  1. JQuery基本脚本:<script type="text/javascript" src="../JQ/jquery.min.js"></script>
  2. EasyUI基本脚本:<script type="text/javascript" src="../JQ/jquery.easyui.min.js"></script>
  3. DataGrid脚本:<script src="../JQ/datagrid-detailview.js" type="text/javascript"></script>

三、Html - body部分: <table id="dg" class="easyui-datagrid"></table>

       若一个页面具有多个表格,即id值不同即可,如

                <div class="dataContent" style="margin-top: 10px">
                    状态统计
                </div>
                <table id="dg" class="easyui-datagrid">
                </table>
                <div class="dataContent" style="margin-top: 10px">
                    状态明细
                </div>
                <table id="dgdetail" class="easyui-datagrid">
                </table>

四、Javascript脚本

       对于动态加载表格数据,一般需要两个步骤:

        (1) 页面加载时初始化表格样式

 1 <script type="text/javascript">
 2         $(function () {
 3            initTable();
 4         });
 5         // 初始化表格
 6         function initTable() {
 7             $('#dg').datagrid({
 8                 width: 1000,   //宽度
 9                 height: 210,    //高度
10                 url: 'StateQuery.aspx',  //请求数据URL
11                 singleSelect: true, //true表示只允许选择一行
12                 onLoadSuccess: function (data) {//当数据加载成功时触发,data为加载数据
13                     loadNoRecord(data);
14                 },
15                 onClickRow: function (rowIndex, rowData) {//当用户点击一行时触发,参数包括:rowIndex:被点击行的索引,从0开始;rowData:被点击行对应的记录 
16                     loadDetail(rowIndex, rowData)
17                 },
18                 columns: [[ //表格对应列的匹配对象
19                     { field: 'ID', width: 40, halign: 'center', title: 'MinRID', hidden: true },
20                     { field: 'CenterName', width: 140, align: 'center', title: '名称' },
21                     { field: 'ClassName', width: 80, align: 'center', title: '班次' },
22                     { field: 'Duration', width: 100, align: 'center', title: '持续时间(分)', formatter: formateFloat },
23                     { field: 'CreateTime', width: 140, align: 'center', title: '日期', formatter: formateDate },
24                     {
25                         field: 'Search', title: '详细信息', width: 100, align: 'center',
26                         formatter: function (value, row, index) {
27                             return '<a href="#" onclick="loadDetail(' + index + ',' + row + ')">查看</a> '
28                         }
29                     }
30                 ]]
31             });
32         }
33         // 数据格式化
34         function formateFloat(data) {
35             if (data == undefined && data == "") return "";
36             return fn.format(data, 2);
37         }
38         // 日期格式化
39         function formateDate(data) {
40             if (data == undefined && data == "") return "";
41 
42             var n = data.indexOf(" ");
43             if (n > 0) return data.substring(0, n);
44             else return data;
45         }
46 </script>
初始化表格

        (2) 通过ajax动态加载表格数据

<input type="button" class="btn_tab" value="查询" onclick="loadTable()" />

<script type="text/javascript">
        //加载数据
        function loadTable() {
            var centerid = $("#hdcenterid").val();

            ajax("ajax=getDataQuery&cid=" + centerid, function (q) {
                    if (!q) { //无数据
                        $("#dg").datagrid("loadData", []);
                    }
                    else { //有数据                     
                        q = json(q);
                        $("#dg").datagrid("loadData", q);
                    }
                });
        }
</script>
动态加载数据

        以上即为实现基本表格所需脚本,如要实现其他功能只需根据EasyUI提供的样例,在初始化表格样式增加相关方法或属性(部分功能见下文)

五、C#后台数据,通过ajax异步回调得到DataTable,其中Column列名需要与初始化表格样式中columns的field完全一致(区分大小写),将其数据转换为json字符返回即可。

using System;
using System.Data;
using iPlant.Component.ProfitCenter;

public partial class Component_ProfitCenter_StateAnalysis_StateQuery : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        #region 异步回调
        if (Request["ajax"] != null)
        {
            string ajax = "";
            if (Request.Form["ajax"] != null || Request.QueryString["ajax"] != null)
            {
                ajax = Request.Form["ajax"] != null ? Request.Form["ajax"] : Request.QueryString["ajax"];
                switch (ajax)
                {
                    case "getDataQuery": ajax = GetDataQuery(); break;//返回状态记录
                    default: break;
                }
                Response.Write(ajax);
                Response.End();
                return;
            }
        }
        #endregion
    }

    private string GetDataQuery()
    {
        int cid = 0;
        if (Request.Form["cid"] != null || Request.QueryString["cid"] != null)
        {
            cid = Request.Form["cid"] != null ? Request.Form["cid"] : Request.QueryString["cid"];
        }

        StateRecordCnfg cnfg = new StateRecordCnfg();
        DataTable dt = cnfg.GetStateRecordQuery(cid);
        return fn.Json(dt);
    }
}
后台数据

六、实现效果

七、表格其他功能

1. 多行表头 : 使用列(Column)属性,Column是一个数组对象,它的每个元素也是一个数组。元素数组的元素是一个配置对象,它定义了每个列的字段。(详见 http://www.jeasyui.net/plugins/183.html

    根据所需表头,使用rowspan(number  指示一个单元格占据多少行)和colspan(number 指示一个单元格占据多少列)进行标记。

 1 function initDetailTable() {
 2             $('#dg').datagrid({
 3                 singleSelect: true,
 4                 width: "96%",
 5                 height: 220,
 6                 columns: [[
 7                     { field: 'Name', width: 120, align: 'center', title: '状态名称', rowspan: 2 },
 8                     { field: 'StateTime', width: 105, align: 'center', title: '开始时间', rowspan: 2 },
 9                     { field: 'EndTime', width: 105, align: 'center', title: '结束时间', rowspan: 2 },
10                     { field: 'Duration', width: 75, align: 'center', title: '持续时间(分)', formatter: formateFloat, rowspan: 2 },
11                     { title: '成本项', align: 'center', colspan: 5 },
12                     { field: 'CreateTime', width: 105, align: 'center', title: '生成时间', rowspan: 2 }
13                 ], [
14                     { field: 'ItemName', width: 80, align: 'center', title: '名称' },
15                     { field: 'UseAmount', width: 60, align: 'center', title: '用量值', formatter: formateFloat },
16                     { field: 'Unit', width: 60, align: 'center', title: '单位' },
17                     { field: 'UnitPrice', width: 60, align: 'center', title: '单价' },
18                     { field: 'UseCost', width: 60, align: 'center', title: '成本', formatter: formateFloat }
19                 ]],
20                 onLoadSuccess: function (data) {
21                     loadCellStyle(data);
22                 }
23             });
24         }
多行表头

    效果图

2. 合并单元格:将信息相同的数据只显示一次,进行同类合并

 1 function loadCellStyle(data) {
 2    if (data.rows != undefined) {
 3        if (data.rows.length > 0) {
 4               var mark = 1;//这里涉及到简单的运算,mark是计算每次需要合并的格子
 5               for (var i = 1; i < data.rows.length; i++) {     //这里循环表格当前的数据
 6                    if (data.rows[i]['StateRecordID'] == data.rows[i - 1]['StateRecordID']) {   //后一行的值与前一行的值做比较,相同就需要合并
 7                        mark += 1;
 8                        $('#dg').datagrid('mergeCells', {
 9                              index: i + 1 - mark,                //datagrid的index,表示从第几行开始合并,就是记住最开始需要合并的位置
10                              field: 'StateName',                 //合并单元格的区域,就是clomun中的filed对应的列,StateName为状态名称
11                              rowspan: mark                       //纵向合并的格数,如果想要横向合并,就使用colspan:mark
12                             });
13 
14                        //合并其他列,只需要修改其field值
15                        $('#dg').datagrid('mergeCells', {
16                              index: i + 1 - mark, 
17                              field: 'CreateTime',                //CreateTime为持续时间(分)
18                              rowspan: mark
19                              });
20                     } else {
21                             mark = 1;                            //一旦前后两行的值不一样了,那么需要合并的格子数mark就需要重新计算
22                     }
23                }
24          }
25          else {
26                     $('#dg .datagrid-view2 .datagrid-body').html('<div style="margin:10px 0; text-align:center;">没有记录.</div>'); //没有记录.
27          }
28      }
29 }
View Code

 效果图:

 

3. 行内编辑及按钮关键点:

  • 待编辑列需要添加editor属性,并且指定编辑时为何控件(type:'combotree'/'combobox'/'text')并指定相关属性(options)
  • 增加方法onBeginEdit和onEndEdit,可用于初始化编辑控件以及赋值
  • 增加toolbar属性,添加编辑按钮
 1         //初始化模版表格
 2         function initdgstate() {//[StateID],[CenterID],[StateCode],[StateName],[SNLength],[SNType] 
 3             $('#dg').datagrid({
 4                 width: $(window).width() - 20,
 5                 height: $(window).height() - 100,
 6                 url: 'State.aspx',
 7                 singleSelect: true,
 8                 rownumbers: true,
 9                 onClickRow: function (rowIndex, row) {
10                     selectRow(rowIndex, row, $("#dg"));
11                 },
12                 onDblClickRow: function () {
13                     //双击选中
14                     fchangeRow();
15                 },
16                 onBeginEdit: function (rowIndex, row) {
17                     var ed = $(this).datagrid('getEditor', { index: rowIndex, field: 'CenterName' });
18                     var st = $(this).datagrid('getEditor', { index: rowIndex, field: 'STStateName' });
19                     var ft = $(this).datagrid('getEditor', { index: rowIndex, field: 'FTStateName' });
20                     var pstate = $(this).datagrid('getEditor', { index: rowIndex, field: 'PStateName' });
21 
22                     //-----------------初始化获得combotree值------------------
23                     $(pstate.target).combotree({
24                         url: 'State.aspx?ajax=getState&cid=' + G("selcenterid").value,
25                         methord: 'get',
26                         onBeforeExpand: function (record) {
27                             $(pstate.target).combotree("tree").tree("options").url = "State.aspx?ajax=getState&cid=" + G("selcenterid").value + "&pid=" + record.id;
28                         },
29                         onSelect: function (record) {
30                             row.PID = record.id;
31                         },
32                         onShowPanel: function () {
33                             if (($(pstate.target).combotree('tree').tree('getRoots').length) == 0) {
34                                 $(pstate.target).combotree('setValue', "");
35                                 row.PID = 0;
36                             }
37                         }
38                     });
39                     if ($(pstate.target).combotree('getValue').length == 0) {
40                         $(pstate.target).combotree('setValue', row.PStateName);
41                     }
42                 },
43                 onEndEdit: function (rowIndex, row) {
44                     //--------------选择combotree结果--------------
45                     var pid = $(this).datagrid('getEditor', { index: rowIndex, field: 'PStateName' });
46                     row.PStateName = $(pid.target).combotree('getText');
47                 },
48                 columns: [[
49                     { field: 'StateID', width: 60, align: 'center', title: '状态编号' },
50                     { field: 'CenterID', width: 100, halign: 'center', title: 'ID', hidden: true },
51                     { field: 'CenterName', width: 120, align: 'center', title: '利润中心 *', editor: 'text' },
52                     { field: 'StateName', width: 120, align: 'center', title: '状态名称  *', editor: 'text' },
53                     { field: 'StateCode', width: 100, align: 'center', title: '代码  *', editor: 'text' },
54                     { field: 'SNLength', width: 90, align: 'center', title: '流水号长度  *', formatter: formateNum, editor: { type: 'numberbox', options: { precision: 0 } } },
55                     {
56                         field: 'SNType', width: 90, align: 'center', title: '流水号类型  *',
57                         formatter: formateType,
58                         editor: {
59                             type: 'combobox',
60                             options: {
61                                 valueField: 'id',
62                                 textField: 'text',
63                                 data: [{ id: "1", text: "天" }, { id: "2", text: "月" }],
64                                 panelHeight: 'auto',
65                                 editable: false
66                             }
67                         }
68                     },
69                     { field: 'PID', width: 100, halign: 'center', title: 'PID', hidden: true },
70                     {
71                         field: 'PStateName', width: 120, align: 'center', title: '上级状态',
72                         editor: {
73                             type: 'combotree',
74                             options: {
75                                 valueField: 'id',
76                                 textField: 'text',
77                                 panelHeight: 'auto',
78                                 editable: false
79                             }
80                         }
81                     }
82                 ]],
83                 toolbar: [
84                     { id: 'addBtn', text: '添加', iconCls: 'icon-add', handler: faddRow }, '-',
85                     { id: 'editBtn', text: '修改', iconCls: 'icon-edit', handler: feditRow }, '-',
86                     { id: 'delBtn', text: '删除', iconCls: 'icon-remove', handler: fdelRow }, '-',
87                     { id: 'saveBtn', text: '保存', iconCls: 'icon-save', handler: fsaveRow }, '-',
88                     { id: 'cancelBtn', text: '取消', iconCls: 'icon-cancel', handler: fcancelRow }, '-',
89                     { id: 'changeBtn', text: '选择', iconCls: 'icon-ok', handler: fchangeRow }]
90             });
91         }
92         //格式化
93         function formateNum(val, row) {
94             if (val != undefined) {
95                 return formatNumber(val, "#.##");
96             }
97         }
View Code

  效果图:

 

 

 

猜你喜欢

转载自www.cnblogs.com/zhangjbravo/p/8047552.html