动态绑定Gridview带模板列
公司要做一个可以支持4种数据库(<!--数据库类型 (DLL专用) (SQL SERVER) (ORACLE) (ACCESS)(POSTGRE SQL)-->)的并且字段随表字段变化的可选可移动顺序的数据查询展示,通过简单工厂+配置文件即可实现,这里不多解释。点击显示设置,将会读取所有数据表中的字段,从而将需要显示的字段进行配置,并且进行排序,这里可以将需要显示的字段按照顺序写入txt文本文件,然后通过获取需要显示 的字段进行动态绑定。
界面效果如下图:
一、动态绑定需要显示的字段(可控制显示顺序)
前台代码:
[html]
<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>
[csharp]
/// <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;