动态绑定Gridview带模板列

  公司要做一个可以支持4种数据库(<!--数据库类型 (DLL专用) (SQL SERVER) (ORACLE) (ACCESS)(POSTGRE SQL)-->)的并且字段随表字段变化的可选可移动顺序的数据查询展示,通过简单工厂+配置文件即可实现,这里不多解释。点击显示设置,将会读取所有数据表中的字段,从而将需要显示的字段进行配置,并且进行排序,这里可以将需要显示的字段按照顺序写入txt文本文件,然后通过获取需要显示 的字段进行动态绑定。

界面效果如下图:


一、动态绑定需要显示的字段(可控制显示顺序)

前台代码:

       <div id="divGvData" runat="server" style="position: relative; top: 0px; left: 0px;
            overflow: auto; width:96%; height:410px;">
            <asp:GridView ID="gvEquData" runat="server" CssClass="usertableborder" OnRowCreated="gvEquData_RowCreated"
                AllowSorting="true" DataKeyNames="SamID" OnRowDataBound="gvEquData_RowDataBound"
                 OnSorting="gvEquData_Sorting" 
                onprerender="gvEquData_PreRender">
                <HeaderStyle CssClass="Freezing" />
                <EmptyDataTemplate>
                    <div style="margin: 0 auto; text-align: center; width: auto; height: auto">
                        没有查询到数据!</div>
                </EmptyDataTemplate>
            </asp:GridView>
        </div>

    /// <summary>
        /// 绑定gridview查询数据
        /// </summary>
        public void BindGridViewData()
        {
            GetWebconfigInfo();
            InitDataInfo();

            try
            {
                GridView gridView = gvEquData;
                gridView.Columns.Clear();
                gridView.AutoGenerateColumns = false;
                string[] selectFields = string.IsNullOrEmpty(shows) ? null : shows.Split(','); //获取所有需要带复选框的列

                BoundField b = new BoundField();
                b.HeaderText = "序号";
                gridView.Columns.Add(b);

                BoundField bf = new BoundField();
                bf.HeaderText = "设备连接状态";
                bf.DataField = "linkStatu";//固定列
                gridView.Columns.Add(bf);

                string[] names = QuarrysClass.All.Split(',');
                string newName;
                if (selectFields == null)
                    return;
                foreach (string name in selectFields)
                {
                    newName = name.Trim('@').ToLower();
                    string colName = resources[newName] == null ? string.Empty : resources[newName].ToString();
                    if (QuarrysClass.CheckFlag.ToLower().IndexOf("@" + newName + "@") != -1) //绑定复选框列
                    {
                      TemplateField tf = new TemplateField();
                        if (resources[newName] == null)
                        {
                            continue;
                        }
                      tf.HeaderTemplate = new GridViewItemTemplate(DataControlRowType.Header, newName, colName, "CheckBox", id);
                        tf.ItemTemplate = new GridViewItemTemplate(DataControlRowType.DataRow, newName, colName, "CheckBox", id);
                        gridView.Columns.Add(tf);
                    }
                    else
                    {
                        if (QuarrysClass.Converts.ToLower().Contains(newName)) //转换显示格式
                        {
                            TemplateField tf = new TemplateField();
                            tf.HeaderTemplate = new GridViewItemTemplate(DataControlRowType.Header, newName, colName, "", id);
                            tf.ItemTemplate = new GridViewItemTemplate(DataControlRowType.DataRow, newName, colName, "Convert", id);
                            gridView.Columns.Add(tf);
                        }
                        else //普通列
                        {
                            bf = new BoundField();
                            bf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                            bf.HeaderText = resources[newName] == null ? string.Empty : colName;
                            bf.DataField = newName;
                            bf.SortExpression = bf.DataField;
                            gridView.Columns.Add(bf);
                        }
                    }
                }

                QuarrysClass.BusNO = txtBusNO == null ? string.Empty : txtBusNO.Text.Trim();
                QuarrysClass.DeviceNO = txtDeviceNO == null ? string.Empty : txtDeviceNO.Text.Trim();
                QuarrysClass.LineNO = txtLineNO == null ? string.Empty : txtLineNO.Text.Trim();
                QuarrysClass.Resources = resources;
                EquSearchBll.equBll.setGridView(gridView, shows);
            }
            catch (Exception)
            {

            }

        }

动态绑定模板列,可以新建一个类GridViewItemTemplate.cs供调用,对于动态绑定的模板列中的textbox,如何在前台通过js获取到,然后一点击选中则通过ajax调用更改状态值是难点,因为你不知道触发的是哪个控件并且更新那个字段的值,这里我通过在动态绑定时,将其ID设置为改行的主键值+列名的形式,这样在前台通过监听所有texbox就可以获取到被点击的chexbox从而实时进行修改状态

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Xiongdi.Common.CommonHelper;
using Xiongdi.BizRul;
using GPRS.Admin;

namespace GPRS
{
    public class GridViewItemTemplate : ITemplate
    {
        private string cType;  //控件对象的字符串,以此来判断具体创建哪个控件
        private DataControlRowType templateType;  //当前行的模板 (Header,item)
        private string colName;  //控件要显示的字符,或是绑定数据源的字段列名
        private string colId; //绑定字段
        private int  dataType=Convert.ToInt32(QuarrysClass.DataType); //数据库类型

        /// <summary>
        /// 主键
        /// </summary>
        public string Id { get; set; }


        /// <summary>
        /// 控件模板
        /// </summary>
        /// <param name="rtype">RowType</param>
        /// <param name="colId">字段ID</param>
        /// <param name="name">字段名称</param>
        /// <param name="cType">模板字段类型</param>
        /// <param name="id">主键</param>
        public GridViewItemTemplate(DataControlRowType rtype, string colId,string name,string cType,string id)
        {
            this.colId = colId;
            colName = name;
            templateType = rtype;
            this.cType = cType;
            this.Id = id;
        }

        private void TexBoxClicking(Object sender, EventArgs e)
        {
         CheckBox cbx = (CheckBox)sender;
         GridViewRow container = (GridViewRow)cbx.NamingContainer;
         //关键位置:使用DataBinder.Eval绑定数据,为此属性赋值(数据源字段)
         cbx.Attributes.Add("onclick", "alert('" + DataBinder.Eval(container.DataItem, colId).ToString() + "');");
        }

        public void InstantiateIn(System.Web.UI.Control container)
        {
            if (templateType == DataControlRowType.Header)
            {
                if (cType == "CheckBox")
                {
                    CheckBox cbxAll = new CheckBox();
                    cbxAll.ID = colId;
                    cbxAll.CssClass = colId;
                    container.Controls.Add(cbxAll);
                }
                Literal ltl = new Literal();
                ltl.Text = colName;
                container.Controls.Add(ltl);
            }
            else if (templateType == DataControlRowType.DataRow)
            {
                if (cType == "CheckBox")
                {
                    CheckBox cbx = new CheckBox();
                    cbx.DataBinding += new EventHandler(cbx_DataBinding); 
                    container.Controls.Add(cbx);
                }
                else if (cType == "Convert")
                {
                    Literal ltl = new Literal();
                    ltl.ID = "lbl" + colId;
                    ltl.DataBinding += new EventHandler(lbl_DataBinding);
                    container.Controls.Add(ltl);
                }
            }
        }

        void lbl_DataBinding(object sender, EventArgs e)
        {
            Literal lbl = (Literal)sender;
            GridViewRow row = (GridViewRow)lbl.NamingContainer;
            if (!string.IsNullOrEmpty(colId))
            {
                lbl.Text =CommonClass.ConvertDateTime(DataBinder.Eval(row.DataItem, colId));
            }
        }

        void cbx_DataBinding(object sender, EventArgs e)
        {
            CheckBox cbx = (CheckBox)sender;
            GridViewRow row = (GridViewRow)cbx.NamingContainer;
           string str=DataBinder.Eval(row.DataItem, colId)==null?string.Empty:DataBinder.Eval(row.DataItem, colId).ToString();
           string id = DataBinder.Eval(row.DataItem, Id) == null ? string.Empty : DataBinder.Eval(row.DataItem, Id).ToString();
           cbx.ID = "cbx_" + id + "-" + colId;
           cbx.CssClass = colId;
           if (dataType == (int)EnumDataType.ACCESS)
           {
               if (str.ToLower() == "true")
               {
                   cbx.Checked = true;
               }
               else
               {
                   cbx.Checked = false;
               }
           }
           else
           {
               if (str =="1")
               {
                   cbx.Checked = true;
               }
               else
               {
                   cbx.Checked = false;
               }
           }
        }
    }
}

更新选中:

        var isReturnStatus = function (data) {
            if (data > 1) {
                searchData();//点击查询按钮
            }
        }
        $(function () {
            $("td").find("input:checkbox").each(function (key, val) {
                $(val).click(function () {
                    var cbxId = $(this).attr("id");
                    var state = $(this).attr("checked")
                    $.post("Ajax/UpdateStatus.ashx", { "id": cbxId, "isChecked": state, "fid": "SamID" }, isReturnStatus);
                });
            });
            $("th").find("input:checkbox").click(
                        function () {
                            if (confirm("确定要更新这一列数据吗?") == true) {
                                var cbxId = $(this).attr("id");
                                var state = $(this).attr("checked");
                                $.post("Ajax/UpdateStatus.ashx", { "id": cbxId, "isChecked": state }, isReturnStatus);
                            }
                        });
        });
    function searchData() {
            var btn = document.getElementById("<%=btnQuery.ClientID %>");
            btn.click();
        }
ajax一般处理文件,用于异步更新选中的checdbox值

  public class UpdateStatus : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            Hashtable ht =EquStatusSearch.ht; //表头选中项状态保持
            int isChecked = context.Request["isChecked"] == "checked" ? 1 : 0;
            string colId=context.Request["id"];
           
            string name = colId.Substring(colId.LastIndexOf('_')+1, colId.Length - colId.LastIndexOf('_')-1);
            int result=0;

            if (QuarrysClass.CheckFlag.ToLower().IndexOf("@" + name + "@") != -1)
            {
                if (ht.ContainsKey(name))
                {
                    ht.Remove(name);
                }
                if (isChecked == 1)
                {
                    ht.Add(name, true);
                }
                else
                {
                    ht.Add(name, false);
                }
                string selectStr = QuarrysClass.StrWhere;
                //控制前台刷新
                result = EquSearchBll.equBll.UpdateAllChecked(name, isChecked, selectStr) == 1 ? 
2 : EquSearchBll.equBll.UpdateAllChecked(name, isChecked, selectStr); 
            }
            else
            {
                if (name.Contains('-'))
                {
                    string idName = context.Request["fid"];
                    string[] arrays = name.Split('-');
                    string id = arrays[0];
                    string fieldName = arrays[1];
                    string strWhere = string.Format(" and {0}='{1}'",idName,id);
                    result = EquSearchBll.equBll.UpdateAllChecked(fieldName, isChecked, strWhere);
                }
            }
           
            context.Response.Write(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
1. 基类说明 1.1 基类结构图 1.2 基类说明 1.2.1 BaseEditClass BaseEditClass是所有单表编辑功能的基类。BaseEditClass从NSGForm继承,以处理统一的界面和字体风格。 BaseEditClass抽象出了编辑类功能通用的方法并定义为基类方法,以便子类继承,并增加自己的代码。  自定义属性 名称 说明 DataTable 功能所编辑的数据表 DataState 功能所处的状态:浏览(dsBrowse)、新增(dsInsert)、编辑(dsEdit) BatchSave 是否批量提交数据表,默认为False DeleteWarn 在删除记录时是否提示,默认为True  自定义方法 名称 说明 FormInit 在FormLoad时被调用,具体功能中可重载该方法添加自定义的初始化代码 PostData 具体功能中需要重载该方法,并调用具体的TableAdapter.Update(row),以保存数据至数据库。 RefreshData 统一的刷新数据表过程,具体功能中需要重载该方法,并调用具体的TableAdapter.Fill(DataTable),以查询数据 DataValid 统一的数据验证方法,在保存数据前被调用。具体功能中可重载该方法添加自定义的数据校验代码 NewRecord 在新增数据时被调用,在具体过程中可重载该方法添加自定义的新增记录默认值 SaveData 保存数据的方法,具体功能中调用该过程保存数据 DeleteData 删除数据的方法,具体功能中调用该过程删除数据 CancelData 取消数据修改的方法,具体功能中调用该过程取消数据修改 1.2.2 BaseGridEdit BaseGridEdit是所有直接使用DataGridView进行编辑的功能的基类。BaseGridEdit从BaseEditClass继承。 自定义属性 名称 说明 Grid 编辑所用的DataGridView 自定义方法 名称 说明 RecordValid 统一的数据验证方法,在单条保存数据前被调用。具体功能中可重载该方法添加自定义的数据校验代码 1.2.3 BaseGridEditForm BaseGridEditForm是所有直接使用DataGridView进行编辑的功能的模板。所有直接使用DataGridView进行编辑的功能都需要从该模板拷贝后进行修改。 2. 模板使用方法 2.1 BaseGridEditForm 使用BaseGridEditForm需要按以下四步操作就可以得到需要的功能。 一、 先从BaseGridEditForm拷贝文件到工程后修改类名、命名空间 二、 在项目的数据集中增加TableAdapter,以查询需要维护的指定的数据表 三、 将DataGridView绑定到新增的数据表 四、 修改以下基类方法 名称 说明 构造方法 增加”DataTable属性=新增数据表”的代码 FormInit 增加需要的Form初始化代码,如RefreshData以获得数据 PostData 增加一行代码:新增的TableAdapter.Update(row) RefreshData 增加使用新增TableAdapter.Fill(DataTable)的代码,以获得查询数据。注意:代码需要写在IsRefreshData = true;和 IsRefreshData = false;语句的中间 RecordValid 增加自定义的数据校验语句。 NewRecord 增加自定义的新增数据默认值代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

邹琼俊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值