动态绑定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 isChecked;
        private int isCheckedAll;
        private int  dataType=Convert.ToInt32(QuarrysClass.DataType); //数据库类型
        private string id; //主键

        /// <summary>
        /// 是否回发
        /// </summary>
        public bool IsAutoPostBack{get;set;}

        public string Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        public string IdValue{get;set;}
       
        public int IsChecked
        {
            get
            {
                return isChecked;
            }
            set
            {
                isChecked = value;
            }
        }
        /// <summary>
        /// 是否全部选中
        /// </summary>
        public int IsCheckedAll
        {
            get
            {
                return isCheckedAll;
            }
            set
            {
                isCheckedAll = value;
            }
        }

        /// <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)
        {
            IsAutoPostBack = true;
            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绑定数据
        //ProName,MyTemplate的属性.在创建MyTemplate实例时,为此属性赋值(数据源字段)
         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.AutoPostBack = IsAutoPostBack;
                    //cbxAll.Attributes.Add("onclick", "javascript:return confirm('确定要更新本列数据吗?');");
                    //cbxAll.CheckedChanged += new EventHandler(cbxAll_CheckedChanged);
                    cbxAll.Checked = Convert.ToBoolean(EquStatusSearch.ht[colId]);
                    cbxAll.ID = colId;
                    container.Controls.Add(cbxAll);
                }
                Literal ltl = new Literal();
                ltl.Text = colName;
                container.Controls.Add(ltl);
            }
            else if (templateType == DataControlRowType.DataRow)
            {
                if (cType == "CheckBox")
                {
                    //HiddenField hdf = new HiddenField();
                    //hdf.ID = "hidf" + colId;
                    //hdf.DataBinding += new EventHandler(this.HiddenFieldxDataBinding);
                    //container.Controls.Add(hdf);

                    CheckBox cbx = new CheckBox();
                    //cbx.AutoPostBack = IsAutoPostBack;
                    //cbx.CheckedChanged += new EventHandler(cbx_CheckedChanged);
                    cbx.DataBinding += new EventHandler(cbx_DataBinding);
                    
                    container.Controls.Add(cbx);
                }
                else if (cType == "Convert")
                {
                    Literal lbl = new Literal();
                    lbl.ID = "lbl" + colId;
                    lbl.DataBinding += new EventHandler(lbl_DataBinding);
                    container.Controls.Add(lbl);
                }
            }
        }

        void cbx_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cbx = (CheckBox)sender;
            IsChecked = cbx.Checked ? 1 : 0;
            string strWhere = string.Format(" {0}='{1}'", this.Id, IdValue);
            EquSearchBll.equBll.UpdateAllChecked(colId, IsCheckedAll, strWhere);
        }

        void cbxAll_CheckedChanged(object sender, EventArgs e)
        {
           CheckBox cbxAll= (CheckBox)sender;
           IsCheckedAll = cbxAll.Checked ? 1 : 0;
           cbxAll.Checked = !cbxAll.Checked;
           EquSearchBll.equBll.UpdateAllChecked(colId, IsCheckedAll,string.Empty);
        }


        void lbl_DataBinding(object sender, EventArgs e)
        {
            Label lbl = (Label)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, colId) == null ? string.Empty : DataBinder.Eval(row.DataItem, Id).ToString();
          cbx.ID = "cbx_" + id + "-" + colId; //这里给chexbox的ID赋予唯一且包含特殊含义的值
           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、本主题所有言论和图片纯属会员个人意见,与码神部落立场无关。
2、本站所有主题由该帖子作者发表,该帖子作者撒浪嘿呦码神部落享有帖子相关版权。
3、码神部落管理员和版主有权不事先通知发贴者而删除本文。
4、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者撒浪嘿呦码神部落的同意。
5、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任。
6、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责。
7、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意。

最新回复 (0)
    • 码神部落
      2
        立即登录 立即注册 GitHub登录
返回
发新帖
作者最近主题: