公司要做一个可以支持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;
}
}
}

动态绑定Gridview带模板列的更多相关文章

  1. 向GridView的模板列绑定OnClientClick的函数时出现了奇怪的问题

    原文:向GridView的模板列绑定OnClientClick的函数时出现了奇怪的问题 GridView的一个模板列中的内容是按钮,需要实现以下的效果: GridView分页显示数据,点击编辑按钮(模 ...

  2. asp.net动态添加GridView的模板列,并获取列值

    一.动态添加模板列: 1.建立模板列样式: 说明:下边代码可以直接写在aspx文件中,也可以单独建立cs文件:另外,我没有写button.linkButton等控件,意思差不多,不过当需要添加事件时, ...

  3. GridView 动态添加绑定列和模板列

    动态添加绑定列很简单:例如: GridView1.DataSourceID = "SqlDataSource1"; BoundField bf1 = new BoundField( ...

  4. GridView绑定数据与隐藏指定控件(模板列)

    1.1.    GridView绑定数据 1)       可以配置SqlDataSource数据源,修改select语句生成框架(不想手动绑定) 2)       删除DataSourceID属性和 ...

  5. js获取gridview模板列中textbox行列的值

    下面一个例子:在gridview中第一列输入数值,第二列输入数值,点击第三列的时候进行计算 求和,如果不符合标记为红色字体. 如图: 代码 : <html xmlns="http:// ...

  6. dotNet平台模板列中的单选无效的解决方案

    最近在grid里添加一个单选列,最开始直接创建一个模板列,然后在模板列里放一个radiobutton.并指定其GroupName.这是radiabutton最常用的方法.但是在Grid里,这样却毫无效 ...

  7. gridview动态添加列的问题

    相信大家也和我一样遇到过这种问题,gridview在生成列的时候当列不确定怎么办?下面分享一下自己的解决方法. 举个列子说明一下. 普通列的添加比较简单. BoundField bf = new Bo ...

  8. 动态绑定GridView数据源遇到问题

    1.GridView中的Button控件响应Command事件的时候出现System.ArgumentException: 回发或回调参数无效, 设置<pages enableEventVali ...

  9. (原创)带模板的OLE输出EXCEL

    其实带模板的OLE输出EXCEL就是将要输出的EXCEL中一些拥有固定值(如标题,表头行等)的单元格先填充好数据和设置好格式后作为模板上传到SAP 中.这样后续在输出EXCEL时只需从SAP中将模板下 ...

随机推荐

  1. .net运行时和核心类库源码(部分源码)微软官方下载

    部分类库代码:http://referencesource.microsoft.com/download.html 运行时clr源码: http://www.microsoft.com/en-us/d ...

  2. HLS 协议

    HTML 5 视频直播一站式扫盲   本文来自于腾讯bugly开发者社区,原文地址:http://bugly.qq.com/bbs/forum.php?mod=viewthread&tid=1 ...

  3. USB接口的SmartCard Class协议标准:ICCD and CCID

    ICCD是 Intergrated Circuit(s) card Device 的缩写.CCID是 Integrated Circuit(s) cards interface devices的缩写I ...

  4. Windows Phone 8本地化多语言支持

    原文 Windows Phone 8本地化多语言支持 在WP8平台处理本地化多语言的支持还是比较容易的,大部分工作都有VS IDE处理,开发者只需简单操作,并翻译本地资源即可实现. 无论您目前的应用是 ...

  5. Runtime.getRuntime().exec(...)使用方法

    Runtime.getRuntime().exec(...)使用方法 如果想要了解更多的信息,参阅代码里面给的链接  下面是这个正确的例子 public class RuntimeExec { /** ...

  6. cocos2d-x游戏开发系列教程-超级玛丽04-AppDelegate

    代码下载链接 http://download.csdn.net/detail/yincheng01/6864893 解压密码:c.itcast.cn 背景 上一篇博文提到在CCApplication: ...

  7. 用JLabel显示时间-- JAVA初学者遇到的一个困难

    问题:用一个JLabe,显示秒数,每过一秒数字自动减少1 问题看似很简单,但对初学JAVA的我来说,还真费了一点劲. 首先是如何即时,可以采用线程的方法: try { Thread.sleep(100 ...

  8. uva11722 - Joining with Friend(几何概率)

    11722 - Joining with Friend You are going from Dhaka to Chittagong by train and you came to know one ...

  9. 我的cocos2d-x集成sharesdk之旅(转)

    链接地址:http://blog.csdn.net/yeungxuguang/article/details/18227153 本文出自:http://www.iteye.com/topic/1130 ...

  10. 树莓派变成一个Web服务器: nginx + php + sqlite

    将树莓派变成一个Web服务器,通过访问网页,就可以控制树莓派,比如:查看摄像头\开灯等等. 一想到Linux Web服务器,我们首先想到的是,Apache + MySql + Php. 树莓派可以安装 ...