jqgrid 动态列生成

前台代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicCol.aspx.cs" Inherits="Content_DynamicCol" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="/Content/smoothness/jquery-ui-1.8.17.custom.css" rel="stylesheet" type="text/css" />
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="/js/jquery.min.js" type="text/javascript"></script>   
    <link href="/js/ui.jqgrid.css" rel="stylesheet" type="text/css" />
    <script src="/js/i18n/grid.locale-cn.js" type="text/javascript"></script>
    <script src="/js/jquery.jqGrid.min.js" type="text/javascript"></script>
    <script src="/js/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="/scripts/jquery.jBox-2.3.min.js"></script>
    <script type="text/javascript" src="/scripts/jquery.jBox-zh-CN.js"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            //首先是获取动态的列
            GetDynamicCols();
            $("#BtnEdit").bind("click", function() {
                var rowid = $("#gridTable").jqGrid('getGridParam', 'selrow');
                if (rowid != null) {
                    var rowData = $("#gridTable").getRowData(rowid);
                    alert(rowData.Device_ID);
                }
                else {
                    alert("请选择数据行");
                }
            }
            );
        }
        );
        function GetDynamicCols() {
            $.ajax({
                type: "POST",
                async: false,
                contentType: "application/json;utf-8",
                url: "Data1.ashx?action=getcols1&orgcode=KEJI11300&ico=true&og=true",
                success: function(data) {
                    creategrid(data);
                },
                beforeSend: function() {
                    //$.jBox.tip("正在查询数据...", 'loading');
                }

            });
        }
        function creategrid(data) {
            $("#gridTable").jqGrid({
                datatype: 'local',
                1200,
                height: 465,
                rowNum: 25,
                rowList: [25, 30, 50],
                shrinkToFit: true, //自动调整列宽
                altRows: true, //隔行变色
                altclass: 'altclass', //隔行变色样式
                colNames: data.ColNs,
                colModel: data.ColMs,
                viewrecords: true,
                caption: "内容列表",
                hidegrid: false,
                ondblClickRow: function(ID) { //行点击事件
                    var rowData = $("#gridTable").jqGrid("getRowData", ID);
                    var id = rowData.OgCode;
                    alert(id);
                },
                loadtext: "正在加载数据......"
            });

            gridTable.addJSONData(data);
        }
        function currencyFmatter(cellvalue, options, rowObject) {
            if (cellvalue = "文件类型")
                return "<img src='http://it.rifa.com.cn/images/new1.gif' />"
            else
                return "文件夹图片URL" + cellvalue
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <table id="gridTable"></table>
        <input id="BtnEdit" type="button" value="修改" />
    </form>
</body>
</html>
后台 Data1.ashx 文件内容

<%@ WebHandler Language="C#" Class="data1" %>
using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Collections;
using System.Configuration;
public class data1 : IHttpHandler {
    RIFATM.DB.SqlHelper sqlh = new RIFATM.DB.SqlHelper();
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";
        DataTable dt = new DataTable();
        DataTable dt2 = new DataTable();
        DataTable resultdata = new DataTable();
        string linkaddres = "";
        string sql = "";
        string sql2 = "";
        if (context.Request.Params["action"] == "getcols1")
        {
            sql = "select * from Sys_home_set where orgcode='" + context.Request.Params["orgcode"].ToString() + "'  and id='7' order by descid asc";
            sql2 = "select sql from Sys_home where orgcode='" + context.Request.Params["orgcode"].ToString() + "'  and id='7'";
        }
        dt = sqlh.GetTable(sql);
        dt2 = sqlh.GetTable(sql2);
        resultdata = sqlh.GetTable(dt2.Rows[0]["sql"].ToString());
        //以下是核心部分
        IList<object> rowObjects = new List<object>();
        ArrayList ColNs = new ArrayList();
        IList<object> ColMs = new List<object>();
        ColNs.Add("");
        var colm = new
        {
            name = "img",
            index = "img",
            width = 32,
            sortable = false
        };
        ColMs.Add(colm);
        ColNs.Add("");
        var colmog = new
        {
            name = "OgCode",
            index = "OgCode",
            hidden = true
        };
        ColMs.Add(colmog);
        Type homecols = ClassHelper.BuildType("homecols");
        List<ClassHelper.CustPropertyInfo> cpo = new List<ClassHelper.CustPropertyInfo>();
        ClassHelper.CustPropertyInfo cpi;
       
        foreach (DataRow dr in dt.Rows)
        {
            ColNs.Add(dr["ColumnText"].ToString());
            var colms = new
            {
                name = dr["ShowColumn"].ToString(),
                index = dr["ShowColumn"].ToString(),
                width = 100
            };
            if (dr["linkaddress"].ToString().Length != 0)
            {
                linkaddres = dr["linkaddress"].ToString();
            }
            cpi=new ClassHelper.CustPropertyInfo("System.String",dr["ShowColumn"].ToString());
            cpo.Add(cpi);
            ColMs.Add(colms);
        }
        ///图标和业务组编码
        if (context.Request.Params["ico"] == "true")
        {
            cpi = new ClassHelper.CustPropertyInfo("System.String", "img");
            cpo.Add(cpi);           
        }
        if (context.Request.Params["og"] == "true")
        {
            cpi = new ClassHelper.CustPropertyInfo("System.String", "OgCode");
            cpo.Add(cpi);
            homecols = ClassHelper.AddProperty(homecols, cpo);
        }
        ///
       
        homecols=ClassHelper.AddProperty(homecols,cpo);
        IList<object> oo = new List<object> { ClassHelper.CreateInstance(homecols) };
        foreach (DataRow dr in resultdata.Rows)
        {
            object o = ClassHelper.CreateInstance(homecols);
            foreach (ClassHelper.CustPropertyInfo _cpo in cpo)
            {
                string colname = _cpo.FieldName;
                if (string.Compare(colname,"img") == 0)
                {
                    ClassHelper.SetPropertyValue(o, "img", "<img src='http://it.rifa.com.cn/images/new1.gif' />");
                }
                if (string.Compare(colname, "OgCode") == 0)
                {
                    ClassHelper.SetPropertyValue(o, "OgCode", "RFHG16000");
                }
                if ((string.Compare(colname, "img") != 0) && (string.Compare(colname, "OgCode") != 0))
                {
                ClassHelper.SetPropertyValue(o, colname, dr[_cpo.FieldName.Trim()].ToString());
                }
            }
            oo.Add(o);
        }
        oo.RemoveAt(0); //不知道为什么生成的第一行数据是NULL,删除空行数据          
        var resultObj = new
        {
            ColNs = ColNs,    // 总页数
            ColMs = ColMs,
            rows = oo
        };
        context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(resultObj));
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

原文地址:https://www.cnblogs.com/your568/p/2735355.html